C++ boost multi_index_容器更改键->;集装箱不正确状态

C++ boost multi_index_容器更改键->;集装箱不正确状态,c++,boost,map,key,boost-multi-index,C++,Boost,Map,Key,Boost Multi Index,假设我们有一个多索引容器: #include <iostream> #include <boost/multi_index_container.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/random_access_index.hpp> #include <boost/multi_index/tag.hpp> #includ

假设我们有一个多索引容器:

#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index/tag.hpp>
#include <boost/multi_index/key_extractors.hpp>

struct A{
A(int i){id=i;}
    int id;
};

typedef boost::multi_index::multi_index_container<
    A * ,
    boost::multi_index::indexed_by<
        boost::multi_index::random_access<
            boost::multi_index::tag<by_insertion>
        >, // this index represents insertion order
        boost::multi_index::hashed_unique<
            boost::multi_index::tag<by_id>,
            boost::multi_index::member<A, int, &A::id>
        >
    >
> MapType;

MapType map;

map.get<1>().insert(new A(1));
map.get<1>().insert(new A(2));

(*map.get<1>().find(1))->id=4; // HERE IF I CHANGE THE KEY, I CAN NOT FIND either key=4 or 1

MapType::nth_index<1>::type::iterator it = map.get<1>().find(4);
if(it != map.get<1>().end() ){
    std::cout << "FOUND A:" << *it << std::endl;
} // DOES NOT WORK?? WHY CANT I FIND the ELement with Key 4?
#包括
#包括
#包括
#包括
#包括
#包括
结构A{
A(inti){id=i;}
int-id;
};
typedef boost::multi_index::multi_index_容器<
A*,
boost::多索引::按索引索引<
boost::多索引::随机访问<
boost::multi_index::tag
>,//此索引表示插入顺序
boost::multi_index::哈希_unique<
boost::multi_index::tag,
boost::multi_index::member
>
>
>地图类型;
地图类型图;
map.get().insert(新的A(1));
map.get().insert(新的A(2));
(*map.get().find(1))->id=4;//在这里,如果我更改键,则找不到键=4或1
MapType::nth_index::type::iterator it=map.get().find(4);
if(it!=map.get().end()){

std::cout不,散列索引不存储散列值,它们总是在运行中计算。为什么要更改键,但继续按旧值查找?

回答Gabriel的最后一条评论:使用指针容器只是为了对元素具有写访问权限,这太过分了。您可以改为执行以下操作之一:

  • 使用
    modify()
    ,检查是否由于触摸了某个键而必须重新定位修改的元素
  • 如果您知道不会更改密钥,请使用
    const\u cast()
    进行强制转换,然后根据需要进行修改

通常,Boost.MultiIndex无法仅向元素的非键部分授予写访问权限。

那么,为什么我找不到键为4的元素
MapType::nth_index::type::iterator it=map.get().find(4);if(it!=map.get().end()){std::cout,因为元素的存储方式是key=1。发生的事情是:*如果你查找4,你会在一个空桶中结束。*如果你查找1,你会发现元素,但在检查key时,这是4,所以查找也会失败。并且,重复我的问题:为什么要这样做?感谢这个令人敬畏的解释!我不想改变ge是关键,但潜在的问题是,如果我只在容器中放置指针,那么我就能够更改元素(容器只有读取权限,使所有A*const类型的延迟迭代器都可以更改A的基础实例)但是,我可以更改我基于容器的键,只要该键在类A中不是常量。这不愚蠢吗?等等:你是在更改你在地图上查找东西的值,并期望地图神奇地知道这一点吗?通常,更改“正在查找的东西”在没有通知容器结果的容器中,UB.Jeah,很抱歉我的错误描述:我希望在这个容器中有指针,我这样做不是为了能够更改对象。这有点微妙,但在我上面的测试中,我偶尔会回避这样一个事实,即容器应该只授予它没有的const访问权限s、 但是对指针没有影响。所以这就是我的问题。我的键在类中必须是常量
const a::id
,因此指向
a
的指针是可以的。使用modify()是一个选项,但有点麻烦。另一个选项是在新类
数据中收集指向
a
的指针和