Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ std Copying a list to map

Consider the following:

struct A
{
    int i;
    double d;
    std::string s;
};

std::list<A> list_A; 

I'd like to copy all the elements of list_A to a map such that every pair in the map will consist of an element from list_A as value and its string s as key. Is there a way of doing it that is more elegant than looping through the list and insert each element along with its string as key to the map?

like image 778
Subway Avatar asked Sep 05 '13 20:09

Subway


2 Answers

This should get you the idea of how to use transform:

std::pair<std::string, A> pairify(const A& a) { return std::make_pair(a.s, a); }

std::transform(list.begin(), list.end(), std::inserter(map, map.end()), pairify);

The reason to use the inserter is:

An insert interator is a special type of output iterator designed to allow algorithms that usually overwrite elements (such as copy) to instead insert new elements automatically at a specific position in the container.

like image 99
Mark B Avatar answered Nov 06 '22 06:11

Mark B


I love standard library algorithms and lambdas but it doesn't get much simpler than:

for (const A& value : list_A) {
    map_A.insert(std::make_pair(value.s, value));
}

The other methods are doing the equivalent of this code and this loop is readable and just as fast.

like image 28
Blastfurnace Avatar answered Nov 06 '22 06:11

Blastfurnace