微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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
immutable and can only be modified through member functions replace
and modify. This precludes the usage of many mutating algorithms that
are nonetheless applicable to std::vectors.

这也适用于ordered indexes.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐