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

C++如何将string类型vector转换为对应int值的关联vector

实现方案

你之前使用std::unordered_multiset的方案不满足需求是因为:该容器仅用于存储可重复的元素集合,无法建立「字符串到唯一自增整数」的映射关系。我们可以通过std::unordered_map完成映射构建,实现逻辑如下:

基础实现代码

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

std::vector<int> map_string_to_id(const std::vector<std::string>& input) {
    std::vector<int> output;
    // 提前预分配容量,避免多次扩容开销
    output.reserve(input.size());
    std::unordered_map<std::string, int> str_to_id;
    int next_id = 0;

    for (const auto& str : input) {
        auto it = str_to_id.find(str);
        if (it == str_to_id.end()) {
            // 首次出现的字符串分配新id
            it = str_to_id.insert({str, next_id}).first;
            next_id++;
        }
        // 存入对应id
        output.push_back(it->second);
    }
    return output;
}

调用示例:

// 输入示例
std::vector<std::string> s {"a","b","a","a","c","d","a"};
auto i = map_string_to_id(s);
// 输出结果为 {0,1,0,0,2,3,0},符合预期

千万级数据优化建议

  • 如果你使用的C版本支持C20,可以使用std::unordered_map的try_emplace方法替代insert,减少重复字符串的构造开销
  • 若允许引入第三方库,使用性能更高的哈希表(如Abseil的absl::flat_hash_map、Boost的boost::unordered_map)可获得30%~50%的性能提升
  • 若已知输入字符串的唯一值数量上限,可以提前给str_to_id调用reserve方法,避免哈希表扩容的重哈希开销

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:45:04