How to Iterate Over a Vector of Pairs in C++?
Last Updated :
02 Feb, 2024
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
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++
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main()
{
vector<pair< int , string> > vec;
vec.push_back({ 1, "Geek" });
vec.push_back({ 2, "for" });
vec.push_back({ 3, "Geeks" });
cout << "Vector Elements:" << endl;
for ( auto pair : vec) {
cout << "Key: " << pair.first
<< ", Value: " << pair.second << endl;
}
return 0;
}
|
Output
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)
Share your thoughts in the comments
Please Login to comment...