Modern C++ idoms and recipes

meshell
1,771 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Previous: Init statement for if/switch Next: Optional

Structured Bindings & Init statement

Possible solution

A possible solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <map>
#include <string>
#include <iostream>
using namespace std::string_literals;
struct address_t {
std::string street;
unsigned plz;
std::string city;
};
int main() {
std::map<std::string, address_t> address_book;
const auto hans = "Hans Meister"s;
const auto hans_address = address_t{"Maihofstrasse 49"s, 6000u, "Luzern"s};
const auto& [it, inserted] = address_book.insert({hans, hans_address});
const auto& [name, address] = *it;
std::cout << "inserted = " << inserted << std::endl;
std::cout << "name = " << name << std::endl;
std::cout << "address = " << address.street << ", "
<< address.plz << ", "
<< address.city << std::endl;
if (const auto it = address_book.find(hans); it != address_book.end()) {
const auto& [name, address] = *it;
std::cout << name << " is in address book living in " << address.city << std::endl;
} else {
std::cout << hans << " is not in address book\n";
}
const auto peter = "Peter Müller"s;
if (const auto it = address_book.find(peter); it != address_book.end()) {
const auto& [name, address] = *it;
std::cout << name << " is in address book living in " << address.city << std::endl;
} else {
std::cout << peter << " is not in address book\n";
}
const auto peter_address = address_t{"Langstrasse 49"s, 8000u, "Zürich"s};
if (const auto& [it, inserted] = address_book.insert({peter, peter_address}); inserted) {
std::cout << "Inserted " << it->first << std::endl;;
} else {
std::cout << "Did not insert " << it->first << std::endl;;
}
if (const auto& [it, inserted] = address_book.insert({peter, peter_address}); inserted) {
std::cout << "Inserted " << it->first << std::endl;;
} else {
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content