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:
#include <iostream>
: This line includes theiostream
library, which provides facilities for input/output through streams.#include <utility>
: This line includes theutility
library, which contains thestd::pair
class template.#include <list>
: This line includes thelist
library, which contains thestd::list
class template, a container that allows constant time insert and erase operations anywhere within the sequence.using namespace std;
: This line allows the program to use names from thestd
namespace without prefixingstd::
before each of them.int main() {...}
: This is the main function where the program execution begins.list<pair<string, int>> people;
: A list of pairs namedpeople
is declared. Each pair contains astring
and anint
, representing a person's name and age respectively.people.push_back(make_pair("Kevin", 49));
: Thepush_back()
function is used to add a pair to the end of the listpeople
. Themake_pair()
function is used to create a pair of a string ("Kevin") and an integer (49).for(const auto& person: people) {...}
: This is a range-based for loop that iterates over each element (person
) in the listpeople
. Theauto
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).cout << "Name: " << person.first << ", Age: " << person.second << "\\n";
: Within the loop, this line prints the name and age of each person. Thefirst
andsecond
members of thepair
class correspond to the person's name and age respectively.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