C++, lesson 7
Real programs juggle many values: the songs in a playlist, the prices on a menu, the scores in a
match. The C++ standard library gives you ready-made containers for this. The two you will
use most are std::vector (a list) and std::map (a dictionary).
A std::vector is a list of values of one type that can grow and shrink. It lives in
<vector>.
The type in angle brackets, <int>, says what the vector holds. Elements are numbered from 0.
v[i] reads or writes element i without checking the index. An index outside the vector is
undefined behaviour.v.at(i) does the same but checks, and throws an exception if is out of range.2 exercises to try what you just read.
iv.empty() tells you whether the vector has no elements.v.pop_back() removes the last element; v.clear() removes them all.Loop over a vector with the range-based for. Use a reference (int&) if you want to change
the elements, and const auto& if you only read them:
size() returns an unsigned type (std::size_t). If you need an index loop, use
std::size_t i as the counter, and be careful with expressions like v.size() - 1 on an empty
vector: unsigned arithmetic wraps around to a huge number instead of going negative.
Watch out for one quirk of brace initialization: std::vector<int> v{5}; is a vector holding
one element, 5. To make five zeros, use parentheses: std::vector<int> v(5);.
A std::map stores key-value pairs, kept sorted by key. Each key appears at most once. It
lives in <map>.
Looking things up needs a little care, because menu[key] inserts the key with a default
value (0 for numbers, empty for strings) if it isn't there yet. To check without inserting, use
find, which returns end() when the key is missing:
menu.count(key) returns 1 or 0, another way to test membership. (C++20 adds contains,
but this course compiles as C++17.)
Looping over a map visits the pairs in key order. Each element has .first (the key) and
.second (the value). C++17 structured bindings unpack them into two names:
Use a vector when order of arrival matters or you access items by position. Use a map when you
look things up by a key such as a name or an id. The maps-and-sets lesson goes deeper, including
std::unordered_map and std::set.
Read daily temperatures (whole numbers) until the input ends and store them in a
std::vector<int>. Print how many days there were, the average with one decimal, and the day
numbers (counting from 1) that were hotter than the average, separated by spaces. If there are
no such days, print none. There is always at least one temperature.
The first line holds a count n. The next n lines each hold a name and a phone number (both
single words). If a name appears twice, the later number replaces the earlier one. After that,
every remaining word is a name to look up: print <name>: <number> or <name>: unknown.
Finally print the whole phone book in alphabetical order under the heading Contacts:.
Use find for the lookups so that unknown names are not added to the map.
#include <vector>
std::vector<int> scores{72, 88, 95};
scores.push_back(60); // add to the end: 72 88 95 60
std::cout << scores.size() << '\n'; // 4
std::cout << scores[0] << '\n'; // 72, the first element
std::cout << scores.back() << '\n'; // 60, the last elementfor (int& s : scores) {
s += 5; // curve every score
}
for (const auto& s : scores) {
std::cout << s << ' ';
}#include <map>
#include <string>
std::map<std::string, double> menu{
{"coffee", 2.50},
{"tea", 1.80},
};
menu["cake"] = 3.20; // add a new pair
menu["tea"] = 1.90; // replace an existing valueif (auto it = menu.find("juice"); it != menu.end()) {
std::cout << it->second << '\n';
} else {
std::cout << "not on the menu\n";
}for (const auto& [item, price] : menu) {
std::cout << item << ": " << price << '\n';
}
// cake, coffee, tea: alphabeticalInput:
18 25 21 30 16
Output:
Days: 5
Average: 22.0
Hot days: 2 4Input:
3
zoe 555-0101
adam 555-0199
mia 555-0123
mia
bob
Output:
mia: 555-0123
bob: unknown
Contacts:
adam 555-0199
mia 555-0123
zoe 555-0101