gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:52:28 24 4
gpt4 key购买 nike

我有一个结构:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com