【问题标题】:inserting " " key into map将“”键插入地图
【发布时间】:2017-07-11 06:19:17
【问题描述】:

在将键、值对插入映射时,如果键为“”并且对应的值存在,将是什么行为。例如

std::map<std::string, std::string> map1;
std::string key = "";
std::string value = "xyz";

map1.insert(std::pair<std::string, std::string>(key, value));

处理这种情况的最佳方法是什么?

【问题讨论】:

  • 您是在问map::insert 是否对空字符串有特殊行为?
  • juanchopanza 有什么特殊行为吗?这种情况有效吗?我怎样才能避免这种特殊情况?
  • 不,没有任何特殊行为,但您的问题暗示它是,或者您还没有阅读map::insert 的任何文档。
  • 或者你认为std::string有一个特殊的状态,“null”。这也不是真的。你所拥有的只是一个空字符串。这会是混乱的根源吗?
  • 啊……非常感谢。纠正自己

标签: c++ templates dictionary stl


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    相关资源
    最近更新 更多