c++ - 如何使用数组的值初始化 unordered_map

标签 c++ c++11 hashmap

我遇到了一段让我感到困惑的代码,unordered_map 的初始化如下所示

std::unordered_map<std::string, int> wordMap;

// Inserting elements through an initializer_list
wordMap.insert({ {"First", 1}, {"Second", 2}, {"Third", 3} } );

但令我惊讶的是下面的代码

int arr[] = { 1, 5, 2, 1, 3, 2, 1 };
unordered_map<int, int> hash; 
    for (int i = 0; i < n; i++) 
        hash[arr[i]]++;

这里我不知道如何在 map 中插入键和值

最佳答案

这里,在unordered_map中,hash[arr[i]]++;是这样工作的:

  1. 它搜索一个键 (arr[i])。如果找到,则相应的值增加1

  2. 如果没有找到,将创建一个新元素,键为 arr[i],因为值是 int 类型,默认值为 0 是为它存储的。因为 ++ 运算符,它会加一。因此,在操作结束时,该值将为 1

为了您的示例非常明确,它的工作方式如下:

i = 0 => arr[i] = 1 => Not present in map => New pair added => hash: [{1, 1}]
i = 1 => arr[i] = 5 => Not present in map => New pair added => hash: [{1, 1}, {5, 1}]
i = 2 => arr[i] = 2 => Not present in map => New pair added => hash: [{1, 1}, {5, 1}, {2, 1}]
i = 3 => arr[i] = 1 => Present in map => Existing pair updated => hash: [{1, 2}, {5, 1}, {2, 1}]
i = 4 => arr[i] = 3 => Not present in map => New pair added => hash: [{1, 2}, {5, 1}, {2, 1}, {3, 1}]
i = 5 => arr[i] = 2 => Present in map => Existing pair updated => hash: [{1, 2}, {5, 1}, {2, 2}, {3, 1}]
i = 6 => arr[i] = 1 => Present in map => Existing pair updated => hash: [{1, 3}, {5, 1}, {2, 2}, {3, 1}]

这里所说的顺序可能与实际顺序不同。以上解释只是为了说明事情。

关于c++ - 如何使用数组的值初始化 unordered_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54494115/

相关文章:

c++ - 在 std::move() 之后删除堆上的结构成员

c++ - 我可以在成员函数上使用 boost::enable_if 吗?

c++ - 如何在 C++ 中将 uint64_t 转换为 const char *?

qt - 是否可以在不使用成员函数的情况下实现 Q_PROPERTY READ/WRITE 访问器?

java - Java有Hashable、Hasher之类的东西吗?

c++ - 对音频信号进行编码是否有任何限制?

c++ - 为什么指向 int 的指针转换为 void* 而指向函数的指针转换为 bool?

c++ - u8R"delim(SomeTextInHere)delim"在 C++ 中是什么意思?

java - 如何使用迭代器 java 将 JSONObject 转换为新 Map 的所有键

c++ - tbb::concurrent_unordered_map::unsafe_erase 是否会使任何现有的迭代器失效?