How to Create a Vector of Pairs in C++?
Last Updated :
21 Feb, 2024
In C++, vectors are dynamic arrays that can store a collection of data. Pairs are data structure to store two different types of objects in the form of key and value. In this article, we will see how to create a vector of pairs in C++.
Vector of Pairs in C++
In C++, you can create a vector of pairs by declaring a std::vector with a std::pair type. It will create a vector container where each element will be a pair consisting of a key and a value. The below syntax shows how to do it:
Syntax
vector<pair<int, char>> myVector;
C++ Program to Create the Vector of Pairs
C++
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main()
{
vector<pair< int , char > > vecOfPairs;
pair< int , char > p1, p2;
p1 = make_pair(1, 'A' );
p2 = make_pair(2, 'B' );
vecOfPairs.push_back(p1);
vecOfPairs.push_back(p2);
for ( const auto & pair : vecOfPairs) {
std::cout << "(" << pair.first << ", "
<< pair.second << ")" << std::endl;
}
return 0;
}
|
Time Complexity: O(N), where N is the number of pairs.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...