C++ “unordered_map”详解

unordered_map 是 C++ 标准库中的一种关联容器,提供了哈希表功能,用于存储键值对。与 std::map 不同,unordered_map 使用哈希表实现,因此元素的存储顺序是无序的,但查找、插入和删除的时间复杂度在平均情况下是常数时间 O(1)

下面是一个关于如何使用 unordered_map 的具体例子,包括插入元素、访问元素、遍历容器等操作。

示例:统计字符串中每个字符出现的次数

#include <iostream>
#include <unordered_map>
#include <string>

using namespace std;

int main() {
    // 定义一个 unordered_map 来存储字符及其出现次数
    unordered_map<char, int> charCount;

    // 示例字符串
    string text = "hello world";

    // 遍历字符串并统计每个字符的出现次数
    for (char c : text) {
        if (c != ' ') {  // 忽略空格
            ++charCount[c];  // 自增字符 c 的出现次数
        }
    }

    // 输出结果
    cout << "Character frequencies:" << endl;
    for (const auto& pair : charCount) {
        cout << pair.first << ": " << pair.second << endl;
    }

    // 查找某个字符的出现次数
    char target = 'o';
    if (charCount.find(target) != charCount.end()) {
        cout << "The character '" << target << "' appears " << charCount[target] << " times." << endl;
    } else {
        cout << "The character '" << target << "' does not appear in the text." << endl;
    }

    return 0;
}

代码说明:

1.定义 unordered_map:

unordered_map<char, int> charCount;
这里定义了一个 unordered_map,用于存储字符(char 类型)和它们的出现次数(int 类型)。

2.遍历字符串并统计字符频率:

for (char c : text) {
    if (c != ' ') {  // 忽略空格
        ++charCount[c];  // 自增字符 c 的出现次数
    }
}

遍历字符串 text 中的每个字符。对于每个字符 c,如果它不是空格,则将 charCount[c] 的值加 1。这将统计每个字符在字符串中出现的次数。

3.遍历 unordered_map 并输出字符频率:

for (const auto& pair : charCount) {
    cout << pair.first << ": " << pair.second << endl;
}

使用 find 方法检查某个字符是否存在于 unordered_map 中。如果存在,输出它的出现次数;否则,输出字符不存在的消息。

输出示例

假设输入字符串为 "hello world",程序的输出将类似于:

Character frequencies:
h: 1
e: 1
l: 3
o: 2
w: 1
r: 1
d: 1
The character 'o' appears 2 times.

unordered_map 的主要操作

  • 插入元素: charCount[c] = count;charCount.insert({c, count});
  • 访问元素: int count = charCount[c];
  • 删除元素: charCount.erase(c);
  • 查找元素: auto it = charCount.find(c);
  • 检查元素是否存在: if (charCount.find(c) != charCount.end())

这个例子展示了如何使用 unordered_map 来有效地统计并查找字符频率,以及如何遍历和操作 unordered_map 中的元素。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值