繁体   English   中英

我如何制作一个 function 来检查一个单词是否在一个向量中重复超过两次或更多次,以及 output 它重复的次数? 在 C++

[英]How could I craft a function that check if a word is repeated more than two time or more in a vector and output the number of time it repeated? in C++

第一次来Stack,希望能跟大家学习。 因此,我的代码涉及用户从文本文件中读取段落并将单词添加到向量中。 该向量将被传递到字数 function 并打印出重复的字数:例如:每个字的计数,年龄 = 2,信念 = 1,最佳 = 1。 it = 10 但是我试图想出一个 function 循环到同一个向量并打印出重复两次以上的单词。 在这种情况下,“它”这个词重复了两次以上。

map<string, int> get_word_count(const vector<string>& words) {
map<string, int> word_count{};

for (string word : words) {
    auto search = word_count.find(word);
    if (search == word_count.end()) {
        word_count[word] = 1;   // not found - add word with count of 1
    }
    else {
        word_count[word] += 1;  // found - increment count for word
    }
}
return word_count;

}

这是我检查向量中重复的许多单词的代码片段。 但是我很难弄清楚如何添加条件来检查单词是否重复两次或两次以上。 如果 word_count > 2,我尝试添加一个条件,然后打印出重复的单词两次。 然而它没有用。 希望各位大侠指点一下,谢谢。

无需检查为std::map自动检查条目是否存在。 如果不是,它会创建一个新的,如果是,则正确处理该值。

只需遍历std::map ,它保存单词与计数,并根据需要使用条件。 查看完整示例。

 int main()
 {   
    std::vector< std::string > words{ "belief","best","it","it","it" };

    std::map< std::string, int > counts;

    for ( const auto& s: words )
    {   
        counts[s]++;
    }   

    for ( const auto& p: counts )
    {   
        if ( p.second > 2 ) { std::cout << p.first << " repeats " << p.second << std::endl; }
    }   
}

暗示:

如果你写auto x: y你会得到 y 的每个元素的副本,这通常不是你想要的。 如果您编写const auto& x: y您将获得对容器元素的 const 引用,这在您的情况下更快/更有效,因为无需创建副本。 编译器也许能够“看到”副本不需要并对其进行优化,但源代码的读者更清楚它的意图是什么!

首先,我真的建议您在编码之前浏览有关 C++ 的文档,您的代码实际上可以通过这种方式重写

map<string, int> get_word_count(const vector<string>& words) {
    map<string, int> word_count{};

    for (string& word : words) {
        word_count[word] += 1;
    }
    return word_count;
}

这是因为 map::operator[](如 unordered_map::operator[])不像 map::at 那样工作(如果密钥不在地图中,则会引发 std::out_of_range 异常)。 不同之处在于 operator[] 返回对给定键的值的引用,如果该键不在 map 中,则将其插入并默认初始化(在您的情况下,int 的值初始化为 0)。 cppreference 上的运算符 []

为了添加“两次或两次以上”部分,您可以通过在 for 循环中添加条件来修改代码。

map<string, int> get_word_count(const vector<string>& words) {
    map<string, int> word_count{};

    for (string& word : words) {
        auto& map_ref = word_count[word];
        map_ref += 1;
        if(map_ref == 2){
        // Here goes your code
        }
    }
    return word_count;
}

如果您对一个单词重复多少次感兴趣,您应该使用循环再次扫描 map。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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