You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何声明键为unordered_map、值为vector<string>的unordered_map?

问题解决:以unordered_map为键的unordered_map声明方法

你的代码编译失败的核心原因是:C++标准库没有为std::unordered_map类型提供默认的哈希函数(std::hash特化),而std::unordered_map的键类型必须具备可哈希能力,因此编译器无法构造这个嵌套的unordered_map对象。

下面提供两种可行的解决方案:

方案一:自定义哈希函数

为unordered_map<char, int>类型编写自定义哈希函数,并在声明外层unordered_map时指定该哈希函数。

完整代码示例

#include <unordered_map>
#include <vector>
#include <string>
#include <functional>

using namespace std;

// 自定义哈希函数结构体,专门处理unordered_map<char, int>
struct HashCharIntMap {
    size_t operator()(const unordered_map<char, int>& map) const {
        size_t hashValue = 0;
        // 遍历map中的每个键值对,组合计算哈希值
        for (const auto& [key, val] : map) {
            // 使用常用的哈希组合方式,降低冲突概率
            hashValue ^= hash<char>()(key) + 0x9e3779b9 + (hashValue << 6) + (hashValue >> 2);
            hashValue ^= hash<int>()(val) + 0x9e3779b9 + (hashValue << 6) + (hashValue >> 2);
        }
        return hashValue;
    }
};

int main() {
    unordered_map<char, int> myMap;
    vector<string> myVector;
    // 声明时指定自定义哈希函数HashCharIntMap
    unordered_map<unordered_map<char, int>, vector<string>, HashCharIntMap> myUnorderedMap;
    myUnorderedMap[myMap] = myVector;
    return 0;
}

说明:

  • std::unordered_map本身已默认支持operator==(标准库为容器提供了相等比较逻辑),无需额外定义相等判断规则。
  • 哈希函数的实现可根据需求调整,只要保证相同内容的unordered_map<char, int>能生成相同哈希值即可。

方案二:转换为可哈希的中间类型

将unordered_map<char, int>转换为天然支持哈希的类型(如std::string),用转换后的类型作为外层unordered_map的键。

完整代码示例

#include <unordered_map>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

// 将unordered_map<char, int>转换为唯一标识的字符串
string mapToKeyString(const unordered_map<char, int>& map) {
    string keyStr;
    // 将键值对存入vector并排序,保证相同内容的map生成相同字符串
    vector<pair<char, int>> sortedPairs(map.begin(), map.end());
    sort(sortedPairs.begin(), sortedPairs.end());
    for (const auto& [key, val] : sortedPairs) {
        keyStr += key;
        keyStr += ':';
        keyStr += to_string(val);
        keyStr += ',';
    }
    return keyStr;
}

int main() {
    unordered_map<char, int> myMap;
    vector<string> myVector;
    // 使用string作为键类型,避免自定义哈希
    unordered_map<string, vector<string>> myUnorderedMap;
    myUnorderedMap[mapToKeyString(myMap)] = myVector;
    return 0;
}

说明:

  • 由于unordered_map本身是无序容器,直接遍历生成字符串可能导致内容相同的map生成不同字符串,因此先将键值对排序再生成字符串,确保唯一性。

内容的提问来源于stack exchange,提问作者Desconocido

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 06:43:28