[英]how to store count of values that are repeated in an array into map in c++?
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.有人请调查一次。
The reason for the error is that list
is an array, which does not have a begin
method (or any other method).错误的原因是list
是一个数组,它没有begin
方法(或任何其他方法)。
This could be fixed by changing the function to take a std::vector
instead of an array.这可以通过将 function 更改为采用std::vector
而不是数组来解决。
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
循环应该改成这样,假设n
是数组的长度:
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;在C和C++中,数组在某种程度上相当于指向数组第一个元素的指针; thus list
gives the start pointer, and list + n
gives a pointer to after the end of the array.因此list
给出了起始指针,而list + n
给出了指向数组末尾之后的指针。
list
is a pointer, it does not have begin
or end
members, nor is it a valid input to std::begin
or std::end
. list
是一个指针,它没有begin
或end
成员,也不是std::begin
或std::end
的有效输入。
If you have n
strings in an array, pointed to by list
, then you can iterate them by constructing a std::span
.如果数组中有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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.