将对象从无序关联容器移动 [英] Move objects from unordered associative container

查看:187
本文介绍了将对象从无序关联容器移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在c ++ 0x移动对象从无序的关联容器?我需要合并两个单独的无序集,我想,如果涉及到价值,回收项目在即将停止的集合。

Is there any way in c++0x of moving objects out from unordered associative containers? I need to merge two separate unordered sets and I would like, in case rvalues are involved, to 'recycle' items in the soon-ceased-to-be sets.

事实上,unordered_set的迭代器只提供对存储项的const引用。我最初认为使用const_cast抛弃常量,但是进一步阅读,似乎这导致未定义的行为。任何建议?

Thing is, unordered_set's iterators provide only const references to the stored items. I had thought initially of using const_cast to throw away the const-ness, but upon further reading it seems this results in undefined behavior. Any suggestion?

编辑

p>

Take this simple-minded example:

#include <string>
#include <unordered_set>

using namespace std;

void merge_sets(unordered_set<string> &s1, unordered_set<string> &&s2)
{
   // Something like this, which (of course) does not work.
   for (auto it = s2.begin(); it != s2.end(); ++it) {
     s1.insert(std::move(*it));
   }
}

int main()
{
   unordered_set<string> s1, s2;
   // Fill first set:
   s1.insert("hello");
   s1.insert("world");
   // Fill second set.
   s2.insert("foo");
   merge_sets(s1,std::move(s2));
   // After this operation, s2 is empty and s1 contains "hello", "world" and "foo".
}

换句话说,我想能够将项目从s2而不是复制它们。应该有一种方法来从一个集合中提取项目,以便该项目被复制/移动,然后从当前集合中删除。

In other words, I would like to be able to move the items from s2 instead of copying them. There should be a way to "extract" items from a set in such a way that the item is copied/moved and then erased from the current set.

推荐答案

为什么不通过使用其中一个作为目标来合并这两个集合,而不是将它们合并到第三个单独的集合?这将至少让你避免从一个源集合复制元素(可能你会选择较大的一个)。

Why not merge the two sets by using one of them as the target, rather than merging them into a third, separate set? This would at least let you avoid copying elements from one of the source sets (presumably you'd choose the larger one).

或者,如果元素是大的,你应当使用智能指针(例如 boost :: shared_ptr<> )间接存储它们,在这种情况下,将容易将指针从两个源复制到目标,从不复制实际对象。

Or, if the elements are large, you should store them indirectly using smart pointers (e.g. boost::shared_ptr<>), in which case it will be easy to copy the pointers from the two sources to the target and never copy an actual object.

这篇关于将对象从无序关联容器移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆