簡體   English   中英

如何將數組中重復的值計數存儲到 c++ 中的 map?

[英]how to store count of values that are repeated in an array into map in c++?

我試圖存儲在字符串數組中重復的單詞數......

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方法(或任何其他方法)。

這可以通過將 function 更改為采用std::vector而不是數組來解決。

如果你想把它保存為一個數組, for循環應該改成這樣,假設n是數組的長度:

for(auto val = list; val != list + n; val++)

在C和C++中,數組在某種程度上相當於指向數組第一個元素的指針; 因此list給出了起始指針,而list + n給出了指向數組末尾之后的指針。

list是一個指針,它沒有beginend成員,也不是std::beginstd::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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM