[英]Unable to access contents of initialized struct in a map
我有一個結構:
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....
當前,我調用使用這些KeyPair的函數。
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中嗎?
你所做的事情畢竟不是那么錯。 您收到編譯器錯誤只是因為編譯器不知道如何將結構數組輸出到cout,所以如果只輸出(* it).first並遍歷(* it).second的元素,那應該沒問題。 但是請注意,您需要以某種方式確保您知道每個此類數組中的條目數。 例如,可以通過始終將某種空條目作為最后一個條目來實現此目的(或者約定,轉義鍵始終是最后一個條目或任何其他形式)
我認為Henning的答案是要走的路。
*gDial
代碼中的*gDial
和*gIP
表示gDial[0]
和gIP[0]
。
因此,您只需將KeyPair
數組的第一個元素插入mMasterList
KeyPair
。
您的pressKeyPairs
的聲明template<size_t nNumOfElements> void pressKeyPairs(KeyPair(&keys)[nNumOfElements]);
本身是正確的。 它將KeyPair
數組作為參數引用。
但是,由於mMasterList
的second_type
是KeyPair
(不是KeyPair
數組), pressKeyPairs((*it).second)
調用類型不匹配錯誤。
以下想法怎么樣?
KeyPair
數組的KeyPairArray
類型 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 );
}
}
希望這可以幫助。
嘗試在typedef聲明后添加Q_DECLARE_METATYPE(KeyPair) ,並調用qRegisterMetaType(“KeyPair”); 在使用KeyPair結構實例之前。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.