c++ - 无法访问映射中已初始化结构的内容

标签 c++ qt data-structures dictionary multimap

我有一个结构:

typedef struct
{
    Qt::Key qKey;
    QString strFormType;
} KeyPair;

现在我初始化 KeyPair 实例,这样我就可以将它用于我的自动化测试应用程序。

KeyPair gDial[] =
{
    { Qt::Key_1 , "MyForm" },
    { Qt::Key_1 , "SubForm" },
    { Qt::Key_Escape, "DesktopForm" }
};

KeyPair gIP[] =
{
    { Qt::Key_1 , "MyForm" },
    { Qt::Key_2 , "Dialog" },
    { Qt::Key_2 , "Dialog" },
    { Qt::Key_Escape, "DesktopForm" }
};
....
and like 100 more instantiations....

目前,我调用了一个使用这些 key 对的函数。

qDebug() << "Testing Test Menu"; 
pressKeyPairs( gDial);

qDebug() << "Testing Browse Menu"; 
pressKeyPairs( gIP);
....
and more calls like this for the rest... 

我想将所有这些 KeyPair 实例化到一个 MAP 中,这样我就不必调用 pressKeyPairs() 和 qDebug() 一百次了……我是使用 MAPS 的新手……所以我尝试了:

map<string,KeyPair> mMasterList;
map<string,KeyPair>::iterator it;   

mMasterList.insert( pair<string, KeyPair>("Testing Test Menu", *gDial) ); //which I know is wrong, but how?
mMasterList.insert( pair<string, KeyPair>("Testing IP Menu", *gIP) );
mMasterList.insert( pair<string, KeyPair>("IP Menu2", *gIP2) );
....

for ( it=mMasterList.begin() ; it != mMasterList.end(); it++ )
{
   qDebug() << (*it).first << endl;
   pressKeyPairs((*it).second);       
   // I don't know how to access .second ... this causes a compiler error
}

编辑: pressKeyPairs 声明为:

template <size_t nNumOfElements> void pressKeyPairs(KeyPair (&keys)[nNumOfElements]); 

此代码块不起作用...:( 有人可以告诉我如何将这些 KeyPairs 正确地放入 Map 中吗?

最佳答案

我认为 Henning 的回答是正确的选择。
*gDial*gIP在您的代码中表示 gDial[0]gIP[0] .
因此,您只插入 KeyPair 的第一个元素排列成 mMasterList .

你的 pressKeyPairs的声明 template<size_t nNumOfElements> void pressKeyPairs(KeyPair(&keys)[nNumOfElements]); 本身是正确的。它引用了 KeyPair数组作为参数。
然而,由于 mMasterListsecond_typeKeyPair (不是 KeyPair 数组), pressKeyPairs((*it).second)调用类型不匹配错误。

下面的想法怎么样?

  • 打字KeyPairArray哪个 指向 KeyPair数组
  • pressKeyPairs引用了 KeyPairArray

例如:

struct KeyPairArray {
  size_t nNumOfElements;
  KeyPair *keys;

  template< size_t N >
  KeyPairArray( KeyPair(&k)[ N ] ) : nNumOfElements( N ), keys( k ) {}
};

// Example
void pressKeyPairs( KeyPairArray const& keys )
{
  for ( size_t i = 0;  i < keys.nNumOfElements;  ++ i ) {
    qDebug()<< keys.keys[ i ].qKey <<','<< keys.keys[ i ].strFormType <<'\n';
  }
}

int main() {
  map<string,KeyPairArray> mMasterList;
  map<string,KeyPairArray>::iterator it;
  mMasterList.insert(
    make_pair( "Testing Test Menu", KeyPairArray( gDial ) ) );

  for ( it=mMasterList.begin() ; it != mMasterList.end(); it++ ) {
    pressKeyPairs( it->second );
  }
}

希望这对您有所帮助。

关于c++ - 无法访问映射中已初始化结构的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4966705/

相关文章:

php - 无法在 PHP 7 中加载类 php-ds 类,因为我收到 fatal error :class not found

algorithm - 美式排序和基数排序有什么区别?

java - 如何设置JAssimp?

c++ - 是否有 Node.js Net API 的 C++ 实现?

c++ - QTConcurrent 不编译

c++ - QSound播放.wav文件时出现意外的null接收器

c - C 语言中字符串输出时就变成了符号

c++ - 无法在 wxWIdgets 3.0 C++ 中连接焦点事件

c++ - 无法捕获屏幕保护程序事件

Windows更改系统分辨率C++