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++
// C++ program to create the Vector of Pairs #include <iostream> #include <utility> #include <vector> using namespace std; // Driver Code int main() { // Declare a vector of pairs, where each pair // contains an integer and a character vector<pair< int , char > > vecOfPairs; // creating pairs pair< int , char > p1, p2; p1 = make_pair(1, 'A' ); p2 = make_pair(2, 'B' ); // inserting pairs to the vector vecOfPairs.push_back(p1); vecOfPairs.push_back(p2); // Iterate over the vector of pairs // using a range-based for loop for ( const auto & pair : vecOfPairs) { std::cout << "(" << pair.first << ", " << pair.second << ")" << std::endl; } return 0; } |
(1, A) (2, B)
Time Complexity: O(N), where N is the number of pairs.
Auxiliary Space: O(N)
How to Create a Vector of Pairs in C++?
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++.