【发布时间】:2011-02-11 05:21:06
【问题描述】:
我的迭代器出现了一些错误,但我还看不到它。
我有一个 Boost MultiIndex 容器 HostContainer hmap,它的元素是 boost::shared_ptr 到类 Host 的成员。所有索引都适用于 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++;
}
什么会导致此代码失败?上面的 sn-p 只在 numFamily > 1 时运行。(也欢迎其他建议和批评。)提前谢谢。
我将 while() 循环替换为
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++;
}
这似乎行得通。
我不太明白这是如何解决的,或者为什么早期的错误只发生在 2 号家庭中。任何见解都将非常受欢迎。
【问题讨论】: