use*_*517 0 c++ stl std map c++11
我想将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;
}
Run Code Online (Sandbox Code Playgroud)
用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";
}
Run Code Online (Sandbox Code Playgroud)