2010-04-22 69 views
1

我在迭代器中犯了一些錯誤,但是我看不到它。在Boost MultiIndex容器中移動equal_range時迭代器失敗

我有一個Boost MultiIndex容器,HostContainer hmap,其元素是boost::shared_ptrHost的成員。所有的索引都適用於Host類的成員函數。第三個索引是Host::getHousehold(),其中household成員變量是int

下面,我試圖遍歷與特定家庭(int hhold2)匹配的主機範圍,並將相應的私有成員變量Host::id加載到數組中。當家庭規模爲2時,我在運行時發現「斷言失敗:(px!= 0),函數操作符 - >,文件/Applications/boost_1_42_0/boost/smart_ptr/shared_ptr.hpp,第418行」錯誤。仍然不能判斷它隨時會發生的家庭大小是2,或如果其他條件必須滿足。)

typedef multi_index_container< 
    boost::shared_ptr<Host>, 
    indexed_by< 
    hashed_unique< const_mem_fun<Host,int,&Host::getID> >, // 0 - ID index 
    ordered_non_unique< const_mem_fun<Host,int,&Host::getAgeInY> >, // 1 - Age index 
    ordered_non_unique< const_mem_fun<Host,int,&Host::getHousehold> > // 2 - Household index 
    > // end indexed_by 
    > HostContainer; 

typedef HostContainer::nth_index<2>::type HostsByHH; 

// inside main() 
int numFamily = hmap.get<2>().count(hhold2); 
int familyIDs[ numFamily ]; 
for (int f = 0; f < numFamily; f++) { 
    familyIDs[ f ] = 0; 
} 
int indID = 0; 
int f = 0; 
std::pair< HostsByHH::iterator, HostsByHH::iterator > pit = hmap.get<2>().equal_range(hhold2); 
cout << "\tNeed to update households of " << numFamily << " family members (including self) of host ID " << hid2 << endl; 
while (pit.first != pit.second) { 
    cout << "Pointing at new family member still in hhold " << (*(pit.first))->getHousehold() << "; " ; 
    indID = (*(pit.first))->getID(); 
    familyIDs[ f ] = indID; 
    pit.first++; 
    f++; 
} 

什麼能做出這樣的代碼會失敗呢?上面的代碼片段只在numFamily> 1時運行。(也歡迎其他建議和批評。)預先感謝您。


我換成

for (HostsByHH::iterator fit = pit.first; fit != pit.second; fit++) { 
    cout << "Pointing at new family member still in hhold " << (*fit)->getHousehold() << "; " ; 
    indID = (*fit)->getID(); 
    cout << "id=" << indID << endl; 
    familyIDs[ f ] = indID; 
    f++; 
} 

這似乎是工作的while()循環。

我不太明白這是如何解決的,或者爲什麼以前的錯誤只發生在2號住戶的情況下。任何見解都會受到歡迎。

回答

1
int numFamily = hmap.get<2>().count(hhold2); 
int familyIDs[ numFamily ]; 

這可能如何工作?這甚至不應該編譯:你無法定義的元素數量可變的數組,numFamily不得不說是一個編譯時間常數,否則你必須定義familyIDs

int *familyIDs= new int[ numFamily ]; 
+0

哇,感謝指出了這一點。它驚人地編譯與gcc 4.2.1。我很困惑,爲什麼。 – Sarah 2010-04-26 19:47:08

+0

這是否解決了原始問題? – 2010-04-27 16:21:42

+0

@Sarah,顯然,它編譯,因爲海灣合作委員會有一個擴展名,讓這種語法(因爲這種語法是允許在C) – sukhmel 2014-11-20 11:48:56