Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a list of values from a map

Tags:

c++

list

map

stl

Is there an stl way to get a list of values from a map?

i.e, I have:

std::map<A,B> myMap;

and I would like a function that will return just the list of values, i.e, std::list<B> (or set for that matter. Is there a built-in stl way to do this?

like image 483
Amir Rachum Avatar asked Nov 16 '10 15:11

Amir Rachum


People also ask

How do I convert a list of objects to a list of maps?

List<Item> list; Map<Key,Item> map = new HashMap<Key,Item>(); for (Item i : list) map. put(i. getKey(),i); Assuming of course that each Item has a getKey() method that returns a key of the proper type.

How do I convert a Map to a collection?

List Listofvalues= map.stream(). collect(Collectors. toCollection(ArrayList::new)); Note: You can collect elements of Stream in an ArrayList, LinkedList, or any other List implementation.

Can we sort the values in Map?

A map is not meant to be sorted, but accessed fast. Object equal values break the constraint of the map. Use the entry set, like List<Map. Entry<...>> list =new LinkedList(map.


1 Answers

A map element is defined as a map::value_type, and the type of it is a pair<A,B>. first is the key and second is the value. You can write a functor to extract second from a value_type, and copy that in to a vector (or a list, or whatever you want.) The best way to do the copying is to use transform, which does just what its name implies: it takes a value of one type and transforms it to a different type of value.

Here's a complete working example:

#include <cstdlib>
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
#include <iostream>
using namespace std;

typedef map<unsigned, string> MyMap;
MyMap my_map;

struct get_second : public std::unary_function<MyMap::value_type, string>
{
    string operator()(const MyMap::value_type& value) const
    {
        return value.second;
    }
};

int main()
{
    my_map[1] = "one";
    my_map[2] = "two";
    my_map[3] = "three";
    my_map[4] = "four";
    my_map[5] = "five";

    // get a vector of values
    vector<string> my_vals;
    transform(my_map.begin(), my_map.end(), back_inserter(my_vals), get_second() );

    // dump the list
    copy( my_vals.begin(), my_vals.end(), ostream_iterator<string>(cout, "\n"));
}

EDIT:

If you have a compiler that supports C++0x lambdas, you can eliminate the functor entirely. This is very useful for making code more readable and, arguable, easier to maintain since you don't end up with dozens of little one-off functors floating around in your codebase. Here's how you would change the code above to use a lambda:

transform(my_map.begin(), my_map.end(), back_inserter(my_vals), [](const MyMap::value_type& val){return val.second;} );
like image 137
John Dibling Avatar answered Nov 04 '22 11:11

John Dibling