Practice mode C++

Assuming standard headers and using namespace std, what does this C++ code print? map<int, int> m; if (m == 0) cout << m.size();

Correct answer A. 1

Explanation

std::map::operator[] never fails: if the key is missing it inserts a new element with a value-initialised mapped value (0 for int) and returns a reference to it. So merely reading m[5] adds an element, the comparison is true and size() is 1. Use find(), count() or contains() (C++20) to test for a key without inserting.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.