如何使用 std::copy 将一张地图复制到另一张地图?
我想将一个 std::map 的内容复制到另一个 std::map 中。我可以使用 std::copy
来实现吗?显然,下面的代码不起作用:
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*
to "取消引用”它并分配一个值(所有值的类型都是 std::pairoperator++
移动到m2
中的下一个空格。这两个操作都不起作用,因为 const int
中的 const
并且没有为任何新元素保留空间。
有什么方法可以让它与 std::copy 一起使用吗?
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 GMan 的答案 --- 但问题是,为什么您想使用
std::copy
?您应该使用成员函数std::map: :插入
代替。You can use GMan's answer --- but the question is, why do you want to use
std::copy
? You should use the member functionstd::map<k, v>::insert
instead.您需要 插入迭代器 的变体:
inserter
在
中定义。它需要一个插入位置(因此是m2.end()
),并返回一个insert_iterator
。You need a variant of an insert iterator:
inserter
is defined in<iterator>
. It requires a place to insert into (hence them2.end()
), and returns aninsert_iterator
.更新:
C++ 98 引入了“=”运算符,它将左侧的元素复制到容器中。 {地图& operator= (const map& x);}
C++ 11 添加了移动语义以从左侧容器 {map& x) 移动所有元素。 operator= (map&& x);}
和初始化列表赋值 {map&运算符= (initializer_listil);
https://www.cplusplus.com/reference/map/map/operator =/
UPDATE:
C++ 98 introduced the '=' operator, which copies the elements from the left into the container. {map& operator= (const map& x);}
C++ 11 added move semantics to move all the elements from the left container {map& operator= (map&& x);}
and initializer list assignment {map& operator= (initializer_list<value_type> il);
}
https://www.cplusplus.com/reference/map/map/operator=/