我试图存储字符串数组中重复的单词计数…
int countWords(string list[], int n)
{
map <string, int> mp;
for(auto val = list.begin(); val!=list.end(); val++){
mp[*val]++;
}
int res = 0;
for(auto val= mp.begin(); val!=mp.end(); val++){
if(val->second == 2) res++;
}
return res;
}
,但我得到错误像:
prog.cpp: In member function int Solution::countWords(std::__cxx11::string*, int):
prog.cpp:14:32: error: request for member begin in list, which is of pointer type std::__cxx11::string* {aka std::__cxx11::basic_string<char>*} (maybe you meant to use -> ?)
for(auto val = list.begin(); val!=list.end(); val++){
^
prog.cpp:14:51: error: request for member end in list, which is of pointer type std::__cxx11::stri.................
谁来帮我查一下。
错误的原因是list
是一个数组,它没有begin
方法(或任何其他方法)。
这可以通过将函数更改为采用std::vector
而不是数组来修复。
如果你想保持它作为一个数组,for
循环应该改变为这样,假设n
是数组的长度:
for(auto val = list; val != list + n; val++)
在C和c++中,数组在某种程度上相当于指向数组第一个元素的指针;因此list
给指针开始,list + n
结束后给一个指针数组。
list
是一个指针,它没有begin
或end
成员,也不是std::begin
或std::end
的有效输入。
如果数组中有n
字符串,list
指向它们,则可以通过构造std::span
来迭代它们。
int countWords(std::string list[], int n)
{
std::map<std::string, int> mp;
for(auto & val : std::span(list, n)){
mp[val]++;
}
int res = 0;
for(auto & [key, value] : mp){
if(value == 2) res++;
}
return res;
}