简体   繁体   中英

How do I sort a map according to another map in c++?

I have two maps:

map< T t, int v> map1;
map< T t, int v> map2;

how could I sort the map2 according to the value of map1? (Or save the result to a vector?) Is there a simply way to achive this?

You cannot sort an std::map . The map is always kept in sorted order of keys. This is an essential invariant of the data structure, and there's nothing you can do do mutate that. Best you can do is to copy the map into a different container and rearrange that one, eg:

std::vector<std::pair<T, int>> v(map1.begin(), map1.end());

As Kerrek said, you can simply construct a std::vector< std::pair< T, int> > from the begin and end iterator of your map, but this will also give you the keys and values. You can use std::transform to only get the values:

std::map<int, int> m = { {1,-1}, {2,-2} };
std::vector<int> v; v.reserve(m.size());
std::transform(m.begin(), m.end(), std::back_inserter(v), 
               [](const std::pair<const int, int>& p)
               { return p.second; });
// or
std::transform(m.begin(), m.end(), std::back_inserter(v), 
               std::bind(&std::pair<const int, int>::second, std::placeholders::_1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM