简体   繁体   中英

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).

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM