如何将std :: map的前N个元素复制到另一个地图?

时间:2014-01-24 00:48:28

标签: c++ c++11 map stl std

我想将std :: map的前N个元素复制到另一个地图。我试过copy_n但是失败了。我怎样才能做到这一点?

#include <iostream>
#include <map>
#include <algorithm>
#include <iterator>
using namespace std;
int main(){
  map<int,int> Map;
  for ( int i=0;i<10;i++) Map[i]=i*i;
  map<int,int> Map2;
  std::copy_n(Map.begin(), 5,  Map2.end());
  return 0;
}

3 个答案:

答案 0 :(得分:6)

使用copy_n?它的工作原理应该是:

#include <algorithm>
#include <iterator>
#include <iostream>
#include <map>

int main() {
    std::map<int, int> m1 { { 1, 2 }, { 2, 9 }, { 3, 6 }, { 4, 100 } }, m2;
    std::copy_n(m1.begin(), 2, std::inserter(m2, m2.end()));

    for (auto const & x : m2)
        std::cout << x.first << " => " << x.second << "\n";
}

答案 1 :(得分:4)

如果你是从头开始构建另一个地图,你可以简单地将它需要的迭代器传递给构造函数:

std::size_t n = ...;

std::map<K, V> m1 = { ... };
std::map<K, V> m2(m1.begin(), std::next(m1.begin(), n));

答案 2 :(得分:0)

如果要创建新地图,可以使用范围构造函数。可以使用范围std :: map :: insert。

插入到现有地图中
// copy 3 elements from map source
std::map<K,V>::iterator first = source.begin();
// can also use std::next if available
std::map<K,V>::iterator last = source.begin();
std::advance(last, 3);

std::map<K,V> m1( other.begin(), last);
m1.insert(first, last);
也可以使用

std :: copy,但是你必须使用std :: inserter作为输出迭代器。