Iterate Over a Vector of Pairs in C++
In C++, we can use the range-based for loop to iterate over each element of the vector of pairs. We can then access the first and second data members of each of the pair containers.
C++ Program to Iterator Over a Vector of Pairs
C++
// C++ Program to Iterate through a Vector of Pairs #include <iostream> #include <utility> #include <vector> using namespace std; int main() { // Declare a vector of pairs vector<pair< int , string> > vec; // Insert pairs inside the vector vec.push_back({ 1, "Geek" }); vec.push_back({ 2, "for" }); vec.push_back({ 3, "Geeks" }); // Iterate through the vector of pairs using range-based // for loop cout << "Vector Elements:" << endl; for ( auto pair : vec) { cout << "Key: " << pair.first << ", Value: " << pair.second << endl; } return 0; } |
Vector Elements: Key: 1, Value: Geek Key: 2, Value: for Key: 3, Value: Geeks
Time Complexity: O(N) where N is the number of elements present in the vector.
Auxilary Space : O(1)
How to Iterate Over a Vector of Pairs in C++?
In C++, vectors are dynamic arrays that allow users to store data in a contiguous memory location while pairs are data structures that allow the users to store two heterogeneous values together in the key-value pair. In this article, we are to learn how we can iterate over a vector of pairs in C++.
For Example,
Input:
myVector = <{1: "Geek"}, {2:" for"}, {3:" Geeks"} >
Output:
Vector Elements:
Key: 1, Value: Geek
Key: 2, Value: for
Key: 3, Value: Geeks