CS253: Software Development with C++

Spring 2020

Pair And Tuple

Show Lecture.PairAndTuple as a slide show.

CS253 Pair And Tuple

pair

pair<string, double> teacher("Jack", 3.42);
cout << teacher.first << " makes $" << teacher.second << "/hour\n";
Jack makes $3.42/hour

pair definition

pair is not much more than this:

template<typename T1, typename T2>
struct pair {
    T1 first;
    T2 second;
};

pair comparison

vector<pair<string, string>> ff = {
    {"Storm", "Johnny"},
    {"Storm", "Sue"},
    {"Grimm", "Ben"},
    {"Richards", "Reed"},
};
sort(ff.begin(), ff.end());
for (auto &p : ff)
    cout << p.second << ' ' << p.first << '\n';
Ben Grimm
Reed Richards
Johnny Storm
Sue Storm

pair & multimap

multimap<string, string> ff = {
    {"Storm", "Johnny"},
    {"Storm", "Sue"},
    {"Grimm", "Ben"},
    {"Richards", "Reed"},
};
for (auto &p : ff)
    cout << p.second << ' ' << p.first << '\n';
Ben Grimm
Reed Richards
Johnny Storm
Sue Storm

tuple

tuple

using person = tuple<string, double, int, bool>;
person orange("DJT", 75, 239, false);
cout << boolalpha
     << "Name:    " << get<0>(orange)      << "\n"
     << "Height:  " << get<double>(orange) << "″\n"
     << "Weight:  " << get<2>(orange)      << "#\n"
     << "Popular: " << get<bool>(orange)   << "\n";
Name:    DJT
Height:  75″
Weight:  239#
Popular: false

Output

You can’t just << a pair or a tuple. What would go between the elements?

pair<int,int> p(1,2);
cout << p.first << '/' << p.second;
1/2
pair<int,int> p(3,4);
cout << p;
c.cc:2: error: no match for 'operator<<' in 'std::cout << p' (operand types are 
   'std::ostream' {aka 'std::basic_ostream<char>'} and 'std::pair<int, int>')