Convert a map to a vector in C++

This is a tutorial on how to convert a map to a vector in C++. Maps are used to store key-value pairs in an ordered way. And so, to store these we need a vector of paired values.

Suppose we have a map of integer keys and integer values.

map<int,int> mp;  //mp[key] =value
mp[5] = 10;
mp[8] = 2;
mp[9] = 6;


To store these we need a vector of integer paired with an integer.

vector<pair<int,int>> vec;
//this vec will store the map as:
[[5,10] , [8,2] , [9,6]]

 

Now let us assume a map of string keys and integer values:

map<string,int> mp1; 
mp1["cake"] = 500;
mp1["jam"] = 100;
mp1["pizza"] =400;

 

To store these we need a vector of string paired with an integer.

vector<pair<string,int>> vec1;
//this vec1 will store the map as:
[["cake",500] , ["jam",100] , ["pizza",400]]

 

So let’s see how we can do this.

Map to vector

The idea to convert a map to vector is to iterate over the map and store the key-value pairs into vector one by one. This can be understood by the following examples:

Example1: Integer key and integer value

#include <bits/stdc++.h>
using namespace std;

int main() {
  map<int,int> mp;
  mp[5] = 10;
  mp[2] = 16;
  mp[9] = 7;
  mp[10] = 6;
  
  vector<pair<int,int>> vec;
  
  for(auto i : mp)   //inserting map values into vector
  {
      vec.push_back(make_pair(i.first,i.second));
  }
  
  for(auto j : vec)
  cout<<j.first<<" : "<<j.second<<endl;
  
  return 0;
}

 

Output:

2 : 16
5 : 10
9 : 7
10 : 6

 

Exmaple2: String key and integer values

#include <bits/stdc++.h>
using namespace std;

int main() {
  map<string,int> mp1;
  mp1["cake"] = 500;
  mp1["jam"] = 100;
  mp1["pizza"] = 400;
  
  vector<pair<string,int>> vec1;
  
  for(auto i : mp1)   //inserting map values into vector
  {
      vec1.push_back(make_pair(i.first,i.second));
  }
  
  for(auto j : vec1)
  cout<<j.first<<" : "<<j.second<<endl;
  
  return 0;
}

Output:

cake : 500
jam : 100
pizza : 400

 

That’s it on how to convert a map into a vector. I hope you understood it.

Leave a Reply

Your email address will not be published. Required fields are marked *