c – 在Boost的多索引容器中获取非const迭代器

前端之家收集整理的这篇文章主要介绍了c – 在Boost的多索引容器中获取非const迭代器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用Boost 1_33_1,我得到一个错误,暗示我的迭代器是一个const迭代器(因为它不会让我从find()中得到结果).
$g++ bmi_iter_tst.cpp 
bmi_iter_tst.cpp: In function ‘void tst(employee_set&)’:
bmi_iter_tst.cpp:32: error: invalid initialization of reference of type ‘employee&’ from expression of type ‘const employee’

我知道我不应该修改任何键值,但我没有,但我仍然需要非const访问sto修改容器元素中的其他数据.

我知道我已经在其他地方成功完成了这项工作,我只是看不出是什么会使这个const.

下面的代码源自原始的boost :: multi_index示例

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>


using boost::multi_index_container;
using namespace boost::multi_index;

struct employee
{
  int         id;
  int         tst;

  employee(int id_):id(id_),tst(0){}
};


struct id{};


typedef multi_index_container<
  employee,indexed_by<
    ordered_unique<
      tag<id>,BOOST_MULTI_INDEX_MEMBER(employee,int,id)> >
> employee_set;


void tst(employee_set& s)
{
  employee_set::index_iterator<id>::type it = s.get<id>().find(11);
  employee& eref = *it;

  eref.tst++;
}

解决方法

来自 random access indices上的MultiIndex文档:

As usual in Boost.MultiIndex,elements of random access indices are@H_502_18@ immutable and can only be modified through member functions replace@H_502_18@ and modify. This precludes the usage of many mutating algorithms that@H_502_18@ are nonetheless applicable to std::vectors.

这也适用于ordered indexes.

猜你在找的C&C++相关文章