C++ how to copy a map to a vector [duplicate]

2019-01-23 13:16发布

This question already has an answer here:

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.

7条回答
狗以群分
2楼-- · 2019-01-23 13:39

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;
}
查看更多
聊天终结者
3楼-- · 2019-01-23 13:42

A map stores a pair -- a key and a value. Which part do you want to copy? Or, do you want to copy both to two distinct vectors?

I want to copy both. Once that's done, I need to figure out how to sort the vector by the second value in the pair.

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());
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-23 13:44

If your purpose is just to sort by the type instead of the key, you might want to look at Boost::Bimap. It lets you access both parts of the map pair as keys. Presumably you could iterate over it in order of the second key just as easily as the first.

查看更多
家丑人穷心不美
5楼-- · 2019-01-23 13:47

You can use a different map (or set) and use transform to do the sorting as you insert:

#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 ());
}

I forgot to add that if you need to do this a lot then it might be better just to use a boost multi-index container.

查看更多
贪生不怕死
6楼-- · 2019-01-23 13:48

If you're using a std::map, it's already sorted by the key. Just create an iterator and iterate over the map from begin() to end() and you're done.

If you'd like to sort by something other than the map key, you can use the same iterator and push a copy of each element onto your vector as you iterate over the map.

查看更多
老娘就宠你
7楼-- · 2019-01-23 13:53
vector<pair<K,V> > v(m.begin(), m.end());

or

vector<pair<K,V> > v(m.size());
copy(m.begin(), m.end(), v.begin());

copy() is in <algorithm>.

查看更多
登录 后发表回答