How to Convert Map to a Vector of Pairs in C++?
Last Updated :
25 Jan, 2024
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++
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< int , char > mp
= { { 1, 'a' }, { 2, 'b' }, { 3, 'c' } };
vector<pair< int , char > > vec;
copy(mp.begin(), mp.end(), back_inserter(vec));
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.
Share your thoughts in the comments
Please Login to comment...