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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2748295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:34:56  来源:igfitidea点击:

How can I copy one map into another using std::copy?

c++stlmapiteratorcopy

提问by Frank

I would like to copy the content of one std::map into another. Can I use std::copyfor that? Obviously, the following code won't work:

我想将一个 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;
}

This won't work because copywill 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 constin const intand there is no space reserved for any new elements.

这不会工作,因为copy会叫operator*m2.begin()为“解引用”,并分配一个值(所有值的类型的std::pair<const int, double>)。然后它会调用operator++移动到 中的下一个空间m2。由于constinconst int并且没有为任何新元素保留空间,因此这两个操作都不起作用。

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

有什么办法可以让它工作std::copy吗?

Thanks!

谢谢!

回答by Billy ONeal

You can use GMan's answer --- but the question is, whydo you want to use std::copy? You should use the member function std::map<k, v>::insertinstead.

您可以使用 GMan 的答案 --- 但问题是,您为什么要使用std::copy?您应该改用成员函数std::map<k, v>::insert

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

回答by GManNickG

You need a variant of an insert iterator:

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

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

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

inserter中定义<iterator>。它需要一个插入的地方(因此是m2.end()),并返回一个insert_iterator.