Show Lecture.PairAndTuple as a slide show.
CS253 Pair And Tuple
pair
- A pair (defined in
<utility>
):
- is a templated
class
- has two
public
data members: .first
and .second
- can be compared to other
pair
s lexicographically.
pair<string, double> teacher("Jack", 3.42);
cout << teacher.first << " makes $" << teacher.second << "/hour\n";
Jack makes $3.42/hour
*map::iterator
returns a pair of key, value.
[0]
and [1]
do not work.
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", "Sue"}, {"Storm", "Johnny"},
{"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
pairs
had to be less-than comparable.
- Primary sort key:
.first
- Secondary sort key:
.second
tuple
- A tuple:
- rhymes with “scruple”
- is defined in
<tuple>
- 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)
- have all comparison methods, lexicographically defined
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>')