c++ - key不存在时map给出的值

标签 c++ stl

假设我有以下功能:

  bool canConstruct(string ransomNote, string magazine) {
    unordered_map<char, int> map(26);
    for (int i = 0; i < magazine.size(); ++i)
        ++map[magazine[i]];
    for (int j = 0; j < ransomNote.size(); ++j)
        if (--map[ransomNote[j]] < 0)
            return false;
    return true;
}

现在假设 ransomNote 有一个 map 中不存在的元素,我通过阅读文档和问题来理解:

What happens if I read a map's value where the key does not exist?

构造了一个新的默认键值 ' '。现在在第二个 for 循环中引用键时,值如何初始化为零?

键对应的值的变化是如何发生的?

是否有相同的文档?

最佳答案

A new default key is constructed having the value ' '.

不,那是错误的。 char“默认” 值为0,对于任何其他整数数字类型也是如此。


Is there any documentation for the same?

std::map::operator[] 的行为被详细记录了 here .

关于c++ - key不存在时map给出的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45129642/

相关文章:

c++ - set.clear() 在删除元素之前调用包含元素的析构函数

c++ - 首次插入静态 STL 集会导致未处理的异常 0xC0000005 : Access violation to be thrown

c++ - `std::sort()` 是否使用线程来提高其性能?

c++ - 将文本日期和时间转换为 ATL::CTime

c++ - QMessageBox 不显示整个标题

c++ - 模板与多态性

c++ - 在图像上应用均值滤波器时出现小的颜色缺陷

c++ - 如何使用 gmock 测试一个类调用它的基类方法

c++ - 使用不同容器、C++、STL 进行排序和查询

c++ - vectorS 的单个迭代器