how to traverse through vector pair
#include <iostream>
#include <vector>
int main() {
std::vector<std::pair<int, char>> vec = {{1, 'a'}, {2, 'b'}, {3, 'c'}};
for (const auto& pair : vec) {
std::cout << "First: " << pair.first << ", Second: " << pair.second << std::endl;
}
return 0;
}
Explanation:
#include <iostream>
and#include <vector>
: Includes necessary libraries for input/output operations and vectors in C++.std::vector<std::pair<int, char>> vec = {{1, 'a'}, {2, 'b'}, {3, 'c'}};
: Defines a vector namedvec
that holds pairs of integers and characters. Initializes the vector with three pairs, each containing an integer and a character.for (const auto& pair : vec) { ... }
: Initiates a loop that iterates through each element in the vectorvec
.const auto& pair
: Defines a reference to each element in the vector aspair
.std::cout << "First: " << pair.first << ", Second: " << pair.second << std::endl;
: Outputs the first and second elements of each pair within the vectorvec
usingstd::cout
. Thepair.first
accesses the first element of the pair (integer) andpair.second
accesses the second element of the pair (character). This output is displayed in the console.return 0;
: Indicates successful completion of themain()
function.