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 named vec 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 vector vec.

  • const auto& pair: Defines a reference to each element in the vector as pair.

  • std::cout << "First: " << pair.first << ", Second: " << pair.second << std::endl;: Outputs the first and second elements of each pair within the vector vec using std::cout. The pair.first accesses the first element of the pair (integer) and pair.second accesses the second element of the pair (character). This output is displayed in the console.

  • return 0;: Indicates successful completion of the main() function.