我有一个包含四个索引的多索引容器。其中一个索引是随机访问索引,用于维护插入顺序。当外部更新容器元素的属性时,我希望更新相关索引。但是,我想保留插入顺序。
我想知道如果我替换有问题的值,是否会影响插入顺序。如果没有,我怎么能实现这个目标?
答案 0 :(得分:2)
我希望modify()可以在这里工作。让我试一试并展示一个例子:
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <iostream>
struct Data
{
int i;
std::string index1;
friend std::ostream& operator<<(std::ostream& os, Data const& v) {
return os << "{ " << v.i << ", '" << v.index1 << "' }";
}
};
namespace bmi = boost::multi_index;
using Table = bmi::multi_index_container<
Data,
bmi::indexed_by<
bmi::random_access<>,
bmi::ordered_unique<bmi::member<Data, std::string, &Data::index1> >
> >;
static std::ostream& operator<<(std::ostream& os, Table const& table) {
os << "insertion order: "; for(auto const& element : table) os << element << "; ";
os << "\nsecondary index: ";for(auto const& element : table.get<1>()) os << element << "; ";
return os << "\n";
}
int main()
{
Table table {
{ 42, "aap" },
{ 43, "noot" },
{ 44, "mies" }
};
std::cout << "Before:\n" << table << "\n";
table.modify(table.begin(), [](Data& v) { v.i *= v.i; });
std::cout << "Edit 1:\n" << table << "\n";
table.modify(table.begin()+2, [](Data& v) { v.index1 = "touched"; });
std::cout << "Edit 2:\n" << table << "\n";
}
打印
Before:
insertion order: { 42, 'aap' }; { 43, 'noot' }; { 44, 'mies' };
secondary index: { 42, 'aap' }; { 44, 'mies' }; { 43, 'noot' };
Edit 1:
insertion order: { 1764, 'aap' }; { 43, 'noot' }; { 44, 'mies' };
secondary index: { 1764, 'aap' }; { 44, 'mies' }; { 43, 'noot' };
Edit 2:
insertion order: { 1764, 'aap' }; { 43, 'noot' }; { 44, 'touched' };
secondary index: { 1764, 'aap' }; { 43, 'noot' }; { 44, 'touched' };
你想要的可能是什么?