boost - 如何在不影响插入顺序的情况下替换多索引容器中的项目?

标签 boost boost-multi-index

我有一个带有四个索引的多索引容器。其中索引之一是随机访问索引,用于维护插入顺序。当容器元素上的属性在外部更新时,我希望更新相关索引。但是,我想保留插入顺序。

我想知道如果替换有问题的值,插入顺序是否会受到影响。如果没有,我怎样才能实现这一目标?

最佳答案

我希望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' }; 

这可能是您想要的?

查看 Live On Coliru

关于boost - 如何在不影响插入顺序的情况下替换多索引容器中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23160321/

相关文章:

c++ - 连通分量 BOOST c++

c++ - boost::flyweight 是否进行引用计数?

c++ - 使用 Boost 时的内存泄漏检测

Boost MultiIndex 作为 LRU 缓存的 C++ 索引排序问题

c++ - 插入 boost multi_index 后找不到

c++ - boost multi_index_container composite_key_compare

c++ - boost posix_time : stringstream input fails

python - C++ boost + Python : undefined reference to Py_Dealloc

c++ - 如何在复合键控提升多索引容器的一个键上执行 equal_range 并在第二个键上执行 lower_bound?

c++ - 返回 boost multi_index 接口(interface)时 C++ 中的 const 混淆