Pair Demo - A List of pairs

Now let's look at creating a List of Pairs

#include <iostream> #include <utility> #include <list> using namespace std; int main() { // Declare a list of pairs list<pair<string, int>> people; // Add pairs to the list people.push_back(make_pair("Kevin", 49)); people.push_back(make_pair("Alice", 36)); people.push_back(make_pair("Bob", 44)); // Print the list cout << "List of people:\n"; for(const auto& person: people) { cout << "Name: " << person.first << ", Age: " << person.second << "\n"; } return 0; }

This is a simple C++ program that uses the Standard Template Library (STL) to create a list of pairs. Each pair contains a person's name and age.

Here's a breakdown:

  1. #include <iostream>: This line includes the iostream library, which provides facilities for input/output through streams.

  2. #include <utility>: This line includes the utility library, which contains the std::pair class template.

  3. #include <list>: This line includes the list library, which contains the std::list class template, a container that allows constant time insert and erase operations anywhere within the sequence.

  4. using namespace std;: This line allows the program to use names from the std namespace without prefixing std:: before each of them.

  5. int main() {...}: This is the main function where the program execution begins.

  6. list<pair<string, int>> people;: A list of pairs named people is declared. Each pair contains a string and an int, representing a person's name and age respectively.

  7. people.push_back(make_pair("Kevin", 49));: The push_back() function is used to add a pair to the end of the list people. The make_pair() function is used to create a pair of a string ("Kevin") and an integer (49).

  8. for(const auto& person: people) {...}: This is a range-based for loop that iterates over each element (person) in the list people. The auto keyword automatically deduces the element type (pair<string, int>), and the & symbol means the loop is iterating by reference (to avoid unnecessary copying of elements).

  9. cout << "Name: " << person.first << ", Age: " << person.second << "\\n";: Within the loop, this line prints the name and age of each person. The first and second members of the pair class correspond to the person's name and age respectively.

  10. return 0;: The main function returns 0, which typically indicates that the program has successfully executed.

 

2024 - Programming 3 / Data Structures - Author: Dr. Kevin Roark