use*_*747 0 c++ templates dictionary stl
在将键,值对插入映射时,如果键为""并且对应该值存在,则行为是什么.例如
std::map<std::string, std::string> map1;
std::string key = "";
std::string value = "xyz";
map1.insert(std::pair<std::string, std::string>(key, value));
Run Code Online (Sandbox Code Playgroud)
处理这种情况的最佳方法是什么?
std::string没有特殊的状态或值"null".初始化的字符串""只是一个空字符串,但它仍然是一个像任何其他字符串一样的字符串.将它用作键时,std::map::insert将执行它始终执行的操作:仅当已存在具有相同键的元素时才插入元素.
请注意,您可以使用返回值的第二个成员检查插入是否成功:
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
Run Code Online (Sandbox Code Playgroud)