Reputation: 395
While inserting key, value pair into a map, What will be the behavior if the key is " " and corresponding that value is present. for example
std::map<std::string, std::string> map1;
std::string key = "";
std::string value = "xyz";
map1.insert(std::pair<std::string, std::string>(key, value));
And what is the best way to handle this scenario?
Upvotes: 1
Views: 4844
Reputation: 227608
std::string
does not have a special state or value "null". A string initialized with ""
is just an empty string, but it is still a string like any other. When using it as a key, std::map::insert
will do what it always does: insert the element only if no element with the same key already exists.
Note that you can check whether the insert succeeded using the second member of the return value:
auto res = map1.insert(std::pair<std::string, std::string>(key, value));
std::cout << std::boolalpha;
std::cout << "Success? " << res.second << '\n'; // Success? true
// try again (and fail)
auto res = map1.insert(std::pair<std::string, std::string>(key, value));
std::cout << "Success? " << res.second << '\n'; // Success? false
Upvotes: 8