Skip to main content

Command Palette

Search for a command to run...

Subtle insertion bug with std::map

Published
•1 min read•View as Markdown
R

I am a C++ developer with expertise in building solutions for onboard embedded devices and products, has a penchant for building REST API backends with Spring boot and Node JS express framework

Skill Cloud: MQTT, IoT, SSL, HTTP, TLS, REST API, curl, Node JS, Express, Java, Spring Boot, MongoDB

If you try to access an element in a std::map using a key that doesn't exist already in the map, it will insert a default-constructed value with that key. This will lead to unexpected behavior if you're not aware that the insertion has occurred.

std::map<int, std::string> cities;
myMap[0] = "Rome";

//inserts default-constructed value "" with key 1
std::string value = myMap[1]; 

//outputs empty string ""
std::cout << value << std::endl;

More from this blog

cppnuggets

15 posts

Just as the name says, we'll enjoy learning C++, one nugget at a time ☕