I was trying to store count of words repeated in an array of string...
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;
}
but I was getting error like:
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.................
someone please look into this once.
CodePudding user response:
The reason for the error is that list
is an array, which does not have a begin
method (or any other method).
This could be fixed by changing the function to take a std::vector
instead of an array.
If you want to keep it as an array, the for
loop should be changed to this, assuming n
is the length of the array:
for(auto val = list; val != list n; val )
In C and C , an array is somewhat equivalent to a pointer to the first element of the array; thus list
gives the start pointer, and list n
gives a pointer to after the end of the array.
CodePudding user response:
list
is a pointer, it does not have begin
or end
members, nor is it a valid input to std::begin
or std::end
.
If you have n
strings in an array, pointed to by list
, then you can iterate them by constructing a 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;
}