Open In App

How to Convert Map to a Vector of Pairs in C++?

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, map containers allow us to store the data in key-value pairs. There might be some cases where you want to convert an entire map into a vector of pairs. In this article, we will learn how to convert a map into a vector of pairs.

Example

Input: map<int,string>mp ={ {1,"one"}, {2,"two"}, {3,"three"}}
Output: vector<pair<int,string>>vec= { (1,"one"), (2,"two"), (3,"three")}
Input: map<int,char>mp ={ {1,'a}, {2,'b'}, {3,'c'}}
Output: vector<pair<int,char>>vec= {(1, 'a'), (2, 'b'), (3, 'c')}

Convert Map to a Vector of Pairs

To convert a map to a vector of pairs, we can use the std::copy method provided by the C++ Standard Template Library (STL) to copy the elements from the map to a vector of pairs. We can use the back_inserter() function to make sure that the elements are inserted at the end of the vector.

C++ Program to Convert Map to Vector of Pairs Using std::copy Method

C++




// C++ Program to illustrate how to Convert Map to Vector of
// Pairs Using std::copy Method
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    map<int, char> mp
        = { { 1, 'a' }, { 2, 'b' }, { 3, 'c' } };
  
    // create a vector of pairs to store the elements of map
    vector<pair<int, char> > vec;
  
    // use the std::copy method to copy the elements from
    // map to vector
    copy(mp.begin(), mp.end(), back_inserter(vec));
  
    // print the vector of pairs
    cout << "Vector Elements:" << endl;
    for (auto& pair : vec) {
        cout << "(" << pair.first << ", " << pair.second
             << " "
             << ") " << endl;
    }
  
    return 0;
}


Output

Vector Elements:
(1, a ) 
(2, b ) 
(3, c ) 

Time complexity: O(N), to traverse the whole map and copy values to vector using the copy method.
Auxilary Space: O(1), as no extra space is used for conversion.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads