我想要一张 <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/