2

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

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

4

1 回答 1

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' }; 

这可能是你想要的?

在Coliru现场观看

于 2014-04-18T20:17:26.913 回答