在将键、值对插入到映射中时,如果键是“”并且相应的值存在,将会出现什么行为。例如
std::map<std::string, std::string> map1;
std::string key = "";
std::string value = "xyz";
map1.insert(std::pair<std::string, std::string>(key, value));
处理这种情况的最佳方法是什么?
发布于 2017-07-11 06:35:11
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
https://stackoverflow.com/questions/45026789
复制