gpt4 book ai didi

c++ - 在 Boost 的多索引容器中获取非常量迭代器

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:05:46 24 4
gpt4 key购买 nike

使用 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’

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

我知道我已经在其他地方成功地做到了这一点,我只是看不出是什么使这个成为常量。

以下代码源自原始的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++;
}

最佳答案

multi_index 不知道您不会更改作为键值的成员。这就是它仅实现 const_iterator 的原因。

如果你想修改非关键成员,你可以使用modify函数。如果您要更改键值,您可以使用 modify_keyreplace 成员函数。您可以获得更多信息 here .

关于c++ - 在 Boost 的多索引容器中获取非常量迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7907707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com