C ++中将一对从地图复制到矢量的最佳方法是什么?我这样做是为了随后对向量进行排序。
Jack BeNimble
问问题
29213 次
7 回答
28
vector<pair<K,V> > v(m.begin(), m.end());
或者
vector<pair<K,V> > v(m.size());
copy(m.begin(), m.end(), v.begin());
copy()
在<algorithm>
.
于 2009-03-26T04:12:19.417 回答
24
这应该做你想要的:
#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;
}
于 2009-03-26T04:31:53.033 回答
6
如果您使用的是 std::map,则它已经按键排序。只需创建一个迭代器并遍历从 begin() 到 end() 的地图,就完成了。
如果您想按地图键以外的其他内容进行排序,则可以使用相同的迭代器,并在迭代地图时将每个元素的副本推送到向量上。
于 2009-03-26T04:05:16.017 回答
2
Amap
存储一对——一个键和一个值。您要复制哪个部分?或者,您想将两者都复制到两个不同vector
的 s 吗?
我想复制两个。完成后,我需要弄清楚如何按对中的第二个值对向量进行排序。
template <class V>
struct sort_by_val {
bool operator()(V const& l, V const& r) {
return // ...
}
};
vector<pair<K, V> > outv(map.begin(), map.end());
sort(outv.begin(), outv.end(), sort_by_val());
于 2009-03-26T04:02:07.943 回答
2
假设您要复制键和值:
std::map<Foo, Bar> m;
// Map gets populated
// (...)
// Copying it to a new vector via the constructor
std::vector<std::pair<Foo, Bar>> v(m.begin(), m.end());
// Copying it to an existing vector, erasing the contents
v.assign(m.begin(), m.end());
// Copying it to the back of an existing vector
v.insert(v.end(), m.begin(), m.end());
于 2009-03-26T04:12:43.847 回答
2
如果您的目的只是按类型而不是键进行排序,您可能需要查看Boost::Bimap。它允许您作为键访问映射对的两个部分。大概您可以像第一个键一样容易地按第二个键的顺序对其进行迭代。
于 2009-03-26T10:48:33.363 回答
0
您可以使用不同的地图(或集合)并在插入时使用转换进行排序:
#include <map>
#include <algorithm>
typedef std::map<unsigned int, signed char> MapType1;
typedef std::map<MapType1::mapped_type, MapType1::key_type> MapType2;
struct SwapPair
{
MapType2::value_type operator()(MapType1::value_type const & v)
{
return std::make_pair (v.second, v.first);
}
};
int main ()
{
MapType1 m1;
for(int i = 0; i < 10; ++i)
m1[i] = i * -i;
MapType2 m2;
std::transform (m1.begin ()
, m1.end ()
, std::inserter (m2, m2.end ())
, SwapPair ());
}
我忘了补充一点,如果您经常需要这样做,那么使用 boost多索引容器可能会更好。
于 2009-03-26T11:02:28.603 回答