簡體   English   中英

如何將std :: map的前N個元素復制到另一個地圖?

[英]How can i copy first N elements of a std::map to another map?

我想將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;
}

使用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";
}

如果要從頭開始構建另一個映射,則只需將其需要的迭代器傳遞給構造函數即可:

std::size_t n = ...;

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

如果要創建新地圖,則可以使用范圍構造函數。 可以使用范圍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作為輸出迭代器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM