C ++如何将地图复制到矢量 [英] C++ how to copy a map to a vector
本文介绍了C ++如何将地图复制到矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C ++中将对从地图复制到向量的最好方法是什么?
What's the best way in C++ to copy a pair from a map to vector? I'm doing this so I can subsequently sort the vector.
推荐答案
这应该可以做你想要的:
This should do what you want:
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <iterator>
using namespace std;
bool cmp(const pair<int, int> &p1, const pair<int, int> &p2)
{
return p1.second < p2.second;
}
int main()
{
map<int, int> m;
for(int i = 0; i < 10; ++i)
m[i] = i * -i;
vector<pair<int, int> > v;
copy(m.begin(), m.end(), back_inserter(v));
sort(v.begin(), v.end(), cmp);
for(int i = 0; i < v.size(); ++i)
cout << v[i].first << " : " << v[i].second << endl;
return 0;
}
这篇关于C ++如何将地图复制到矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文