c++ - 无法在 C++ 中将 <string, int> 与 char* 作为字符串对

标签 c++ string dictionary

我想要一张 <string, int> 的 map .我试图将给定字符串的单个字符作为键值对的键。但是,我遇到了这个错误:

Line 7: no matching function for call to 'std::unordered_map<std::__cxx11::basic_string<char>, int>::find(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)'

这是我的代码:

int lengthOfLongestSubstring(string s) {
    unordered_map<string, int> map;
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (map.find(s[i]) == map.end()) {
            count++;
            map.insert(make_pair<string, int>(s[i], 1));
        } else {
            map.clear();
            count = 0;
        }
    }

    return count;
}

我认为错误是因为 s[i] 变成了 char*,所以我不能做 make_pair,因为 char* 和 string 是不同的类型。

我试图通过以下方式解决这个问题:

string temp(s[i]); // Try to create a string from the char* and pass it into the make_pair function

但是,我仍然遇到同样的错误。

最佳答案

I think the error is because s[i] becomes a char* and so I cannot do make_pair since char* and string are different types.

不,what s[i] returns只是一个 char(更准确地说,一个 char& 引用),不能直接转换为 std::string。要从 char 构造 std::string,您需要使用 std::string 的不同构造函数,即:

basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() )

例如:

map.insert(make_pair<string, int>(string(1, s[i]), 1));

或者:

map.insert(make_pair<string, int>({1, s[i]}, 1));

关于c++ - 无法在 C++ 中将 <string, int> 与 char* 作为字符串对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47213969/

相关文章:

r - 拆分字符串并重新排列数据框

c++ - 保留对象成员变量的本地拷贝

c++ - 为什么 GCC 优化掉这个增量?

javascript - 加入并替换多次出现的字符串

list - "bad words"过滤器

python - 从 json 文件加载项目描述

python - 动态创建字典键,我可以在其中附加附加值?

c++ - 如何在不删除 .o 文件的情况下使用 makefile 进行编译?

C++ | Windows - 将 STL 对象传递给 DLL

c - linux下C如何区分字符串中的数据类型?