【问题标题】:how to store count of values that are repeated in an array into map in c++?如何将数组中重复的值的计数存储到c ++中的map中?
【发布时间】:2021-11-27 13:16:06
【问题描述】:

我试图存储在字符串数组中重复的单词数...

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 只是一个指向 std::string 的指针。即使您使用了-&gt;beginend 也很可能不是您想要的(因为这将是一个单一的 std::string 的迭代器)

标签: c++ arrays dictionary stl


【解决方案1】:

错误的原因是list是一个数组,它没有begin方法(或任何其他方法)。

可以通过将函数更改为采用 std::vector 而不是数组来解决此问题。

如果要保持为数组,for循环应该改成这样,假设n是数组的长度:

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

在 C 和 C++ 中,数组在某种程度上等同于指向数组第一个元素的指针;因此list 给出了开始指针,list + n 给出了指向数组末尾之后的指针。

【讨论】:

  • list 不是数组。它是一个指针。可能它确实指向数组的第一个元素,但区别很重要,因为对于数组,可以使用 std::beginstd::end
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2018-07-04
    • 2019-07-23
    • 2021-08-23
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2021-07-04
    相关资源
    最近更新 更多