#include using std::cin; using std::cout; using std::endl; #include #include void test_map() { std::map msi; msi.insert(std::make_pair("Kalle", 1)); msi.emplace("Lisa", 2); msi["Kim"] = 3; for (const auto &a : msi) { cout << a.first << " : " << a.second << endl; } cout << "Kim --> " << msi.at("Kim") << endl; cout << "Lisa --> " << msi["Lisa"] << endl; cout << "Hans --> " << msi["Hans"] << endl; // [] default-konstruerar ett värde // för nycklar som inte finns try { cout << "Nisse --> " << msi.at("Nisse") << endl; } catch (std::out_of_range &e) { cout << "Nisse not found: " << e.what() << endl; } const auto &kim = msi.find("Kim"); if (kim != msi.end()) { cout << "Kim : " << kim->second << endl; } else { cout << "Kim not found\n"; } auto nisse = msi.find("Nisse"); if (nisse != msi.end()) { cout << "Nisse : " << nisse->second << endl; } else { cout << "Nisse not found\n"; } } void test_set() { std::set ints{1, 3, 7}; ints.insert(5); for (auto x : ints) { cout << x << " "; } cout << endl; auto has_one = ints.find(1); if (has_one != ints.end()) { cout << "one is in the set\n"; } else { cout << "one is not in the set\n"; } if (ints.count(1)) { cout << "one is in the set\n"; } else { cout << "one is not in the set\n"; } auto has_two = ints.find(2); if (has_two != ints.end()) { cout << "two is in the set\n"; } else { cout << "two is not in the set\n"; } if (ints.count(2)) { cout << "two is in the set\n"; } else { cout << "two is not in the set\n"; } auto has_five = ints.find(5); if (has_five != ints.end()) { cout << "five is in the set\n"; } else { cout << "five is not in the set\n"; } ints.erase(5); auto has_five_now = ints.find(5); if (has_five_now != ints.end()) { cout << "five is in the set\n"; } else { cout << "five is not in the set\n"; } } void test_set_bounds() { std::set ints{9, 1, 3, 7, 5}; auto lb3 = ints.lower_bound(3); cout << "lb3: " << *lb3 << endl; auto ub3 = ints.upper_bound(3); cout << "ub3: " << *ub3 << endl; auto lb4 = ints.lower_bound(4); cout << "lb4: " << *lb4 << endl; auto ub4 = ints.upper_bound(4); cout << "ub4: " << *ub4 << endl; auto er = ints.equal_range(7); if (er.first == er.second) { cout << "er.first == er.second"; } cout << ", er.first: " << *er.first << ", er.second: " << *er.second << endl; } int main() { test_map(); test_set(); test_set_bounds(); }