tags:

views:

86

answers:

2
std::map<std::string, int> m;
// Can I make assumption that m["NoSuchKey"] will return 0?
std::cout << m["NoSuchKey"] << std::endl;
+9  A: 

Yes. When an item is accessed through operator[] that does not exist, it is created with a default-constructed value, and returned.

For numeric types, default-constructed means 0.

GMan
Downvoter reason?
GMan
+3  A: 

Yes. If the map key is not found, a default value will be inserted.

Specifically, operator[] is understood as:

(*((m.insert(value_type(k, data_type()))).first)).second

Translated to your case, m["NoSuchKey"] means

std::pair<std::string, int> pair_to_insert ("NoSuchKey", 0);
// default value of int is 0.
std::pair<std::map<std::string, int>::iterator, bool>
    insert_res = m.insert(value_to_insert);
std::map<std::string, int>::iterator iter_of_inserted_pair = insert_res.first;
std::pair<std::string, int> inserted_pair = *iter_of_inserted_pair;
int inserted_value = inserted_pair.second;
return inserted_value;

In particular, m.insert returns the old key-value pair if the key already exists, and the new key-value pair if not. Therefore, you'll get the expected value if the key already exists, and 0 (the default value) if not.

KennyTM