如何使用 std::copy 将一张地图复制到另一张地图?

发布于 2024-08-30 14:00:23 字数 634 浏览 2 评论 0 原文

我想将一个 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::pair)。然后它会调用operator++移动到m2中的下一个空格。这两个操作都不起作用,因为 const int 中的 const 并且没有为任何新元素保留空间。

有什么方法可以让它与 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;
}

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.

Is there any way to make it work with std::copy?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

黯然#的苍凉 2024-09-06 14:00:23

您可以使用 GMan 的答案 --- 但问题是,为什么您想使用 std::copy?您应该使用成员函数 std::map: :插入 代替。

m2.insert(m1.begin(), m1.end());

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());
离鸿 2024-09-06 14:00:23

您需要 插入迭代器 的变体:

std::copy(m1.begin(), m1.end(), std::inserter(m2, m2.end()) );

inserter 中定义。它需要一个插入位置(因此是 m2.end()),并返回一个 insert_iterator

You need a variant of an insert iterator:

std::copy(m1.begin(), m1.end(), std::inserter(m2, m2.end()) );

inserter is defined in <iterator>. It requires a place to insert into (hence the m2.end()), and returns an insert_iterator.

心安伴我暖 2024-09-06 14:00:23

更新:
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=/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文