我正在使用 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/