Embercode
✕
Maps and Sets (C++)Quick quiz

Map and set bug hunt

8 questions. Covers Debugging lab: map and set pitfalls.

Questions 1 to 5 of 8

  1. 1. This code should check whether bob has votes, then print the number of entries. What is the bug? ``cpp #include <iostream> #include <map> #include <string> int main() { std::map<std::string, int> votes = {{"ann", 2}}; if (votes["bob"] == 0) { std::cout << "bob has no votes\n"; } std::cout << votes.size() << "\n"; } ``
  2. 2. What does this program print? ``cpp #include <iostream> #include <set> int main() { std::set<int> s = {3, 4, 5, 6, 7, 8}; for (auto it = s.begin(); it != s.end(); ) { if (*it % 2 == 1) { it = s.erase(it); } else { ++it; } } for (int x : s) std::cout << x << " "; std::cout << "\n"; } ``
  3. 3. Which call checks whether the key k is in a std::map named m, without inserting anything and without throwing an exception?
  4. 4. A program looks up a name in an unordered_map. What is the bug? ``cpp #include <iostream> #include <string> #include <unordered_map> int main() { std::unordered_map<std::string, int> ages = {{"ann", 31}}; std::cout << ages.find("bob")->second << "\n"; } ``
  5. 5. This loop should erase every entry whose value is 0. What is the bug? ``cpp #include <iostream> #include <map> int main() { std::map<int, int> m = {{1, 0}, {2, 0}, {3, 5}}; for (auto it = m.begin(); it != m.end(); ) { if (it->second == 0) { it = m.erase(it); } ++it; } for (const auto& [k, v] : m) std::cout << k << "=" << v << "\n"; } ``

5 question(s) left on this page.