0

我有一个结构:

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....

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

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 中吗?

4

3 回答 3

1

毕竟你所做的并没有那么错。你得到一个编译器错误只是因为编译器不知道如何将你的结构数组输出到 cout,所以如果你只是输出 (*it).first 并遍历 (*it).second 的元素你应该没问题. 但是请注意,您需要以某种方式确保您知道每个此类数组中的条目数。例如,这可以通过始终将某种空条目作为最后一个条目来实现(或约定转义键始终是最后一个条目或其他)

于 2011-02-11T07:52:22.270 回答
1

我认为亨宁的答案是要走的路。
*gDial*gIP在您的代码中表示gDial[0]gIP[0]
因此,您只将KeyPair数组的第一个元素插入到mMasterList.

pressKeyPairs的声明 template<size_t nNumOfElements> void pressKeyPairs(KeyPair(&keys)[nNumOfElements]); 本身是正确的。它将对KeyPair数组的引用作为参数。
但是,由于mMasterList'ssecond_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 );
  }
}

希望这可以帮助。

于 2011-02-11T15:11:27.717 回答
0

尝试在 typedef 声明后添加Q_DECLARE_METATYPE(KeyPair)并调用qRegisterMetaType("KeyPair"); 在使用KeyPair结构实例之前。

于 2011-02-11T07:51:59.947 回答