How to copy all Values from a Map to a Vector in C++

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.

// Map of string & int
// To store the frequency count of words
std::map<std::string, int> wordMap = { { "is", 6 }, { "the", 5 },
		{ "hat", 9 }, { "at", 6 }, { "of", 2 }, { "hello", 1 } };

Now let’s fetch all values from this map in a vector of int i.e.
6 , 9 , 1 , 6 , 2 , 5

Copy all values from a map to vector using Range Based for Loop

 /*** Copy all value fields from map to a vector using Range Based For Loop ***/
 for(auto elem : wordMap)
	 vecOfValues.push_back(elem.second);

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

// Vector of int to store values
 std::vector<int> vecOfValues;
 vecOfValues.reserve(wordMap.size());

/*** Copy all value fields from map to a vector using Lambda function ***/
std::for_each(wordMap.begin(), wordMap.end(),  [&](std::pair<const std::string, int>  & element){
													vecOfValues.push_back(element.second);
												});

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

Advertisements

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

// Vector of int to store values
std::vector<int> vecOfValues2;
vecOfValues2.reserve(wordMap.size());

/*** Copy all value fields from map to a vector using transform() & Lambda function ***/
std::transform (wordMap.begin(), wordMap.end(),back_inserter(vecOfValues2), [] (std::pair<std::string, int> const & pair)
																				{
																					return pair.second;
																				});

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.

/*
 * Template function that returns 2nd Value from a pair
 */
template <typename K, typename V>
V getSecond(std::pair<K, V> const & pair)
{
	return pair.second;
}

Now use this template function instead of lambda function in std::transform() to copy all values to vector i.e.
// Vector of int to store values
std::vector<int> vecOfValues3;
vecOfValues3.reserve(wordMap.size());

/*** Copy all values from a map to vector using transform() & function pointer ***/
std::transform (wordMap.begin(), wordMap.end(),back_inserter(vecOfValues3), &getSecond<std::string, int>);

Complete example is as follows,
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <utility>
#include <functional>

/*
 * Template function that returns 2nd Value from a pair
 */
template <typename K, typename V>
V getSecond(std::pair<K, V> const & pair)
{
	return pair.second;
}

int main() {

	// Map of string & int
	// To store the frequency count of words
	std::map<std::string, int> wordMap = { { "is", 6 }, { "the", 5 },
			{ "hat", 9 }, { "at", 6 }, { "of", 2 }, { "hello", 1 } };

	/*
	 * Copy all Values from a Map to a Vector using different techniques
	 */

	// Vector of int to store values
	 std::vector<int> vecOfValues;
	 vecOfValues.reserve(wordMap.size());

	 /*** Copy all value fields from map to a vector using Range Based For Loop ***/
	 for(auto elem : wordMap)
		 vecOfValues.push_back(elem.second);

	 // Print contents of vector
	std::copy(vecOfValues.begin(), vecOfValues.end(), std::ostream_iterator<int>(std::cout, " , ") );
	std::cout<<std::endl;

	// Clear the vector
	vecOfValues.clear();

	/*** Copy all value fields from map to a vector using Lambda function ***/
	std::for_each(wordMap.begin(), wordMap.end(),  [&](std::pair<const std::string, int>  & element){
														vecOfValues.push_back(element.second);
													});

	// Print contents of vector
	std::copy(vecOfValues.begin(), vecOfValues.end(), std::ostream_iterator<int>(std::cout, " , ") );
	std::cout<<std::endl;


	// Vector of int to store values
	std::vector<int> vecOfValues2;
    vecOfValues2.reserve(wordMap.size());

	/*** Copy all value fields from map to a vector using transform() & Lambda function ***/
	std::transform (wordMap.begin(), wordMap.end(),back_inserter(vecOfValues2), [] (std::pair<std::string, int> const & pair)
																					{
																						return pair.second;
																					});

	// Print contents of vector
	std::copy(vecOfValues2.begin(), vecOfValues2.end(), std::ostream_iterator<int>(std::cout, " , ") );
	std::cout<<std::endl;

	// Vector of int to store values
	std::vector<int> vecOfValues3;
	vecOfValues3.reserve(wordMap.size());

	/*** Copy all values from a map to vector using transform() & function pointer ***/
	std::transform (wordMap.begin(), wordMap.end(),back_inserter(vecOfValues3), &getSecond<std::string, int>);


	// Print contents of vector
	std::copy(vecOfValues3.begin(), vecOfValues3.end(), std::ostream_iterator<int>(std::cout, " , ") );
	std::cout<<std::endl;

	 return 0;
}

Output:
6 , 9 , 1 , 6 , 2 , 5 , 
6 , 9 , 1 , 6 , 2 , 5 , 
6 , 9 , 1 , 6 , 2 , 5 , 

Thanks.

 

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top