Question 10
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> stock{{"pen", 3}, {"ink", 0}};
int restock = 0;
for (std::string item : {"pen", "ink", "bag"}) {
if (auto it = stock.find(item); it == stock.end()) std::cout << item << ":missing ";
else if (it->second == 0) { std::cout << item << ":empty "; ++restock; }
else std::cout << item << ':' << it->second << ' ';
}
switch (auto n = stock.size(); n) {
case 2: std::cout << "| two items"; break;
default: std::cout << "| " << n;
}
std::cout << " | restock " << restock << '\n';
return 0;
}
- A pen:3 ink:empty bag:missing | two items | restock 1 Correct
- B pen:3 ink:0 bag:missing | two items | restock 0
- C pen:3 ink:empty bag:missing | 3 | restock 1
- D pen:3 ink:empty bag:empty | two items | restock 2
Correct Answer: Option A
it is visible in every branch of the if/else chain. find() never inserts, so the map still has two entries.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!