How can I copy one map into another using std::copy?(如何使用 std::copy 将一张地图复制到另一张地图中?)
问题描述
我想将一个 std::map 的内容复制到另一个.我可以使用 std::copy 吗?显然,下面的代码是行不通的:
I would like to copy the content of one std::map into another. Can I use std::copy for that? Obviously, the following code won't work:
int main() {
typedef std::map<int,double> Map;
Map m1;
m1[3] = 0.3;
m1[5] = 0.5;
Map m2;
m2[1] = 0.1;
std::copy(m1.begin(), m1.end(), m2.begin());
return 0;
}
这不起作用,因为 copy 将调用 m2.begin() 上的 operator* 以取消引用"它并分配一个值(所有值的类型都是 std::pair).然后它会调用 operator++ 移动到 m2 中的下一个空间.这两个操作都不起作用,因为 const int 中的 const 并且没有为任何新元素保留空间.
This won't work because copy will call operator* on m2.begin() to "dereference" it and assign a value (all values are of type std::pair<const int, double>). Then it will call operator++ to move to the next space in m2. Both of these operations don't work because of the const in const int and there is no space reserved for any new elements.
有没有办法让它与 std::copy 一起工作?
Is there any way to make it work with std::copy?
谢谢!
推荐答案
你可以使用 GMan 的答案 --- 但问题是,为什么你要使用 std::copy代码>?您应该使用成员函数 std::map<k, v>::insert 代替.
You can use GMan's answer --- but the question is, why do you want to use std::copy? You should use the member function std::map<k, v>::insert instead.
m2.insert(m1.begin(), m1.end());
这篇关于如何使用 std::copy 将一张地图复制到另一张地图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 std::copy 将一张地图复制到另一张地图中?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
