我使用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文档中进行了搜索,也许我遗漏了什么。谢谢你的建议!
注:对于可能的英语错误,我深表歉意:)
发布于 2011-07-06 13:51:58
使用relocate
http://www.boost.org/libs/multi_index/doc/reference/rnd_indices.html#rearrange_operations
发布于 2011-07-06 08:53:16
使用modify_key怎么样?我以前做过类似的事情,虽然在我的例子中索引不是随机访问的,但我想它可能对您也适用。
https://stackoverflow.com/questions/6590463
复制相似问题