【问题标题】:Iterator failure while moving over equal_range in Boost MultiIndex container在Boost MultiIndex容器中移动equal_range时迭代器失败
【发布时间】: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 号家庭中。任何见解都将非常受欢迎。

【问题讨论】:

    标签: c++ boost iterator


    【解决方案1】:
    int numFamily = hmap.get<2>().count( hhold2 );
    int familyIDs[ numFamily ];
    

    这怎么可能起作用?这甚至不应该编译:您不能定义具有可变数量元素的数组,numFamily 必须是编译时间常数,否则您必须将familyIDs 定义为

    int *familyIDs= new int[ numFamily ];
    

    【讨论】:

    • 哇,感谢您指出这一点。它惊人地与 gcc 4.2.1 一起编译。我很困惑为什么。
    • @Sarah,很明显,它编译是因为 gcc 有一个扩展,它允许这种语法(因为这种语法在 C 中是允许的)
    猜你喜欢
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多