2011-02-10 25 views
0

訪問初始化結構的內容我有一個結構:無法從向量

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

現在我初始化密鑰對實例,所以我可以用它爲我自動測試應用程序。

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

KeyPair gBrowseMenu[] = 
{ 
    { Qt::Key_1 , "MyForm" }, 
    { Qt::Key_2 , "Dialog" }, 
    { Qt::Key_Escape, "DesktopForm" } 
}; 

and like 100 more instantiations.... 

當前,我調用了一個使用這些KeyPair的函數。

pressKeyPairs(gTestMenu); 
pressKeyPairs(gBrowseMenu); 
and more calls for the rest... 

我願把所有這些密鑰對實例的載體,所以我也不會打電話給pressKeyPairs()一百倍。我是一個新手在使用矢量...所以我嘗試:

std::vector<KeyPair, std::allocator<KeyPair> > vMasterList; 
vMasterList.push_back(*gTestMenu); 
vMasterList.push_back(*gBrowseMenu); 

std::vector<KeyPair, std::allocator<KeyPair> >::iterator iKeys; 
for(iKeys = vMasterList.begin(); iKeys != vMasterList.end(); ++iKeys) 
{ 
    pressKeyPairs(*iKeys); 
} 

但是,此代碼塊不工作... :(有人可以告訴我如何正確地把這些密鑰對的載體

回答

2

您對使用insert填充載體?與你的不同陣列。這是你應該怎麼做。

//initialized with one array 
std::vector<KeyPair> vMasterList(gTestMenu, gTestMenu + 3); 

//adding more items 
vMasterList.insert(vMasterList.end(), gBrowseMenu , gBrowseMenu + 3); 

然後再重新實現你的pressKeyPair功能,使您可以使用std::for_each<algorithm>頭文件,

//pressKeyPair will be called for each item in the list! 
std::for_each(vMasterList.begin(), vMasterList.end(), pressKeyPair); 

這裏是你如何寫pressKeyPair功能:

void pressKeyPair(KeyPair &keyPair) //takes just one item! 
    { 
     //press key pair! 
    } 

在我的看法是,這是更好的設計,因爲它不再需要在呼叫站點「手動」循環!

你甚至可以叫pressKeyPair爲在列表中第一個5個項目,

//pressKeyPair will be called for first 5 items in the list! 
std::for_each(vMasterList.begin(), vMasterList.begin() + 5, pressKeyPair); 

再舉一個例子:

//pressKeyPair will be called for 5 items after the first 5 items, in the list! 
std::for_each(vMasterList.begin()+5, vMasterList.begin() + 10, pressKeyPair); 

編輯:

如果你想使用手動循環,那麼你必須使用這個:

std::vector<KeyPair>::iterator it; 
for(it = vMasterList.begin(); it != vMasterList.end(); ++it) 
{ 
    pressKeyPair(*it); 
} 

但是我會說這不像前面描述的方法那樣優雅。請記住,這是假定功能pressKeyPair有這樣的簽名:

void pressKeyPair(KeyPair &keyPair); //it doesn't accept array! 
+0

In std :: vector vMasterList(gTestMenu,gTestMenu + 3); 3從哪裏來?謝謝...... :) – Owen 2011-02-10 08:00:09

2

我覺得現在的問題是,代碼

vMasterList.push_back(*gTestMenu); 

只增加的gTestMenu單個元素的矢量,即第一。原因是這個代碼相當於以下內容:

vMasterList.push_back(gTestMenu[0]); 

從中我可以更容易地看到哪裏出了問題。

要解決此問題,您可能需要將gTestMenu中的所有元素添加到主列表中。您可以使用三參數vector::insert功能做到這一點:

vMasterList.insert(v.begin(), // Insert at the beginning 
        gTestMenu, // From the start of gTestMenu... 
        gTestMenu + kNumTests); // ... to the end of the list 

在這裏,你需要指定多少測試是在gTestMenukNumTests。你可以這樣做gBrowseMenu

順便說一句,如果您只想使用默認的std::allocator,則不需要在vector聲明中指定分配器類型。你可以寫

std::vector<KeyPair> vMasterList; 

而且你會很好。