In this article we will discuss how to fetch all values from a map and put them in vector.

Suppose we have a map of words and their frequency count i.e.

Now let’s fetch all values from this map in a vector of int i.e.

Copy all values from a map to vector using for_each() & Lambda function

Iterate over each entry in map and call lambda function on each entry. Which will put second field from given pair to the vector.

Copy all values from a map to vector using transform() and lambda function

std::transform will iterate over each entry in map and call given lambda function on it. Then pass the result returned by it to the vector’s back_inserter.

Copy all values from a map to vector using transform() & function pointer

We can also call the std::transform() with a function pointer i.e. let’s create a template function that returns second value from a given pair i.e.

Now use this template function instead of lambda function in std::transform() to copy all values to vector i.e.

Complete example is as follows,

Output:

Thanks.

 

Click Here to Subscribe for more Articles / Tutorials like this.