Show Lecture.PairAndTuple as a slide show.
CS253 Pair And Tuple
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;
};
- I consider it to be a cheap
struct
for very local use.
- For wider use, make a
struct
with mnemonic names.
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
- For
sort()
to work, the pair
s had to be less-than comparable.
- Primary sort key:
.first
- Secondary sort key:
.second
- Did you notice the valid trailing comma?
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
- A
map
is not much more than a set
of pair
s.
- I needed a
multimap
because there are two Storm siblings.
- Two-level sorting: first by
.first
, second by .second
.
- A
tuple
:
- rhymes with “scruple”
- is defined in
<tuple>
- sort of an extension of
pair
- has as many fields as you like
- does not have
.first
, .second
, .third
, etc.
- has non-methods
get<0>(
tuple)
,
get<1>(
tuple)
, get<2>(
tuple)
, etc.
- These are compile-time indices.
[0]
, [1]
, … do not work.
- has non-method
get<
type>(
tuple)
- has all comparison methods
(
<
, >
, <=
, >=
, ==
, !=
),
lexicographically defined
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>')