c++ - 如何在不删除元素并将其重新插入到 boost::multi_index_container 的情况下移动元素?

标签 c++ boost multi-index

我正在使用 boost::multi_index_container提供对元素集合的随机访问和基于散列的访问。我想更改元素的随机访问索引,而不更改基于哈希的索引。

这是一段代码:

# include <string>
# include <boost/multi_index_container.hpp>
# include <boost/multi_index/random_access_index.hpp>
# include <boost/multi_index/hashed_index.hpp>
# include <boost/multi_index/member.hpp>

using namespace std ;
using namespace boost ;
using namespace boost::multi_index ;

// class representing my elements
class Element
{
    public :
      Element(const string & new_key) : key(new_key) {}
      string key ;      // the hash-based index in the multi_index_container
      // ... many stuff skipped
    private :
      // ... many stuff skipped
} ;

typedef multi_index_container<
            Element,
            indexed_by<
                random_access< >,
                hashed_unique<
                    member<Element, string, &Element::key>
                >
            >    
        > ElementContainer ;

typedef ElementContainer::nth_index<0>::type::iterator ElementRandomIter ;
typedef ElementContainer::nth_index<1>::type::iterator ElementHashedIter ;

int main(int, char*[])
{
    ElementContainer ec ;

    // insert some elements
    ec.push_back(Element("Alice")) ;       // random-access index = 0
    ec.push_back(Element("Bob")) ;         // random-access index = 1
    ec.push_back(Element("Carl")) ;        // random-access index = 2
    ec.push_back(Element("Denis")) ;       // random-access index = 3

    // Here I want to move "Denis" to position 1
    // The (bad looking) solution I found involves removing and inserting the element
    ElementRandomIter it = ec.get<0>().begin() + 3 ;
    Element e = *(it) ;                    // store a copy
    ec.get<0>().erase(it) ;                // remove the element
    it = ec.get<0>().begin() + 1 ;
    ec.get<0>().insert(it, e) ;            // insert the copy

    // Elements are now in the following order
    // random-access index 0 : Alice
    // random-access index 1 : Denis
    // random-access index 2 : Bob
    // random-access index 3 : Carl

    return 0 ;
}

我知道,即使我在这个例子中只使用随机访问迭代器来操作元素,散列在 multi_index_container 中至少在幕后发生两次,除了一个对象拷贝,它可以很贵。

是否有一种方法可以更改 boost::multi_index 中元素的随机访问索引,而不需要昂贵的删除和插入同时保持复制丑陋?

我在multi_index_container 文档中搜索过,也许我遗漏了什么。感谢您的任何建议!

注意:对于可能出现的英文错误,我们深表歉意:)

最佳答案

关于c++ - 如何在不删除元素并将其重新插入到 boost::multi_index_container 的情况下移动元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6590463/

相关文章:

python - 如何从未堆叠的 Pandas 数据框中选择特定列?

c++ - 指针++,未定义的行为

c++ 自定义运算符 (+=) 以不可预测的方式运行

c++ - std::async 和 std::future 行为

c++ - wxWidgets 安装时 header 路径不正确

boost - 使用 boost syslog 和 cpp-netlib 时出现段错误

boost - 使用boost库的缺点?

c++ - boost 累加器示例不编译

python - 如何在多索引数据框中按第二级日期切片进行过滤

python - 访问 Pandas 数据框中内部多索引级别的最后一个元素