[英]C++11 STL merge using move assignment between 2 maps
Is it possible to merge map from 1 instance A to another without unnessery calls of copy constructor of B? 是否有可能将映射从1个实例A合并到另一个实例,而不需要对B的复制构造函数进行不必要的调用?
class A
{
...
A & operator=(A && rhs);
map<string, B> map;
};
class B
{
B();
B & B(B && rhs);
...
}
...
A instanceOfA1;
A instanceOfA2;
B instanceOfB1;
B instanceOfB2;
B instanceOfB3;
B instanceOfB4;
instanceOfA1.map.insert( pair<string, B>("one", instanceOfB1));
instanceOfA1.map.insert( pair<string, B>("two", instanceOfB2));
instanceOfA1.map.insert( pair<string, B>("three", instanceOfB3));
instanceOfA2.map.insert( pair<string, B>("four", instanceOfB4));
instanceOfA2 = instanceOfA1;
So that map in instanceOfA2 contains all four instances of B. 因此instanceOfA2中的map包含B的所有四个实例。
EDIT: Fixed instances in code. 编辑:修复代码中的实例。
Is it possible to merge map from 1 instance A to another without unnessery calls of copy constructor of B?
是否有可能将映射从1个实例A合并到另一个实例,而不需要对B的复制构造函数进行不必要的调用?
Unfortunately, no. 很不幸的是,不行。 There was a proposal to allow elements to be removed from one map and inserted into another, but it was not accepted.
有人建议允许从一个地图中删除元素并将其插入另一个地图中,但不接受。 There are some plans to revise the paper and make a new proposal in future.
有一些计划在未来修改该文件并提出新的提案。
The best you can do is to insert new elements, but make sure they use the move constructor of B
instead of copying: 您可以做的最好是插入新元素,但要确保它们使用
B
的移动构造函数而不是复制:
for (auto& p : A1)
A2.insert(std::move(p));
This can be done with move_iterator
s too: 这也可以通过
move_iterator
来完成:
A2.insert(std::make_move_iterator(A1.begin()), std::make_move_iterator(A1.end()));
Note that the key_type
in a std::map
is const
, so the key type can not be moved, only the mapped types (the B
objects) will be moved. 请注意,
std::map
中的key_type
是const
,因此无法移动键类型,只会移动映射类型( B
对象)。 That means A1
will still contain the same number of elements it had originally, but the B
objects will be moved-from, and so you probably want to do this afterwards: 这意味着
A1
仍将包含与原来相同数量的元素,但B
对象将被移动,因此您可能希望之后执行此操作:
A1.clear();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.