【问题标题】:How to count number of times word is repeated in C++如何计算单词在C++中重复的次数
【发布时间】:2017-01-31 21:01:33
【问题描述】:

您好,我在使用此代码时遇到了一些问题。

【问题讨论】:

  • 为什么不简单地使用std::unordered_map<std::string, int> 将单词映射到其频率?

标签: c++ string sorting vector


【解决方案1】:

计算唯一词的最佳方法是使用std::unordered_map<std::string, int>,然后在映射中递增值:wordMap[word]++; 请注意,如果这是单词的第一次出现,将创建默认值,它是 0,即非常适合这项任务。

除此之外,当有 std::sort 时,最好自己实现排序,这在大多数情况下都很好。

【讨论】:

  • 抱歉我只能使用冒泡排序
【解决方案2】:

冒泡排序:

vector<string> strings = split(str);
for (int i = 0; i < strings.size(); i++) {
    for (int j = 0; j < strings.size() - 1; j++) {
        if (strings[j + 1] < strings[j]) {
            string tmp = strings[j];
            strings[j] = strings[j + 1];
            strings[j + 1] = tmp;
        }
   }
}

点餐后数词:

string prev = strings[0];
int counter = 1;

for (int i = 1; i < strings.size(); i++) {
    if (strings[i] == prev) {
        counter++;
    } else {
        cout << prev << ": " << counter << " ";
        prev = strings[i];
        counter = 1;
    }
}

【讨论】:

  • 我应该在最后做一个计数器将它添加到vector字符串吗?
  • 添加什么?向量中的字符串只是交换了
  • 还要跟踪每个单词的重复次数。输出示例:“这是一个测试” this: 1 is: 2 a: 1 test: 1
  • 谢谢。我收到“意外类型名称”的错误除了 我还需要导入一些库吗?
  • 不,除了iostream、vector和string,我没有任何库
【解决方案3】:

您可以使用 std::find from algorithm:

std::find(strings.begin(), strings.end(), the_word_you_looking_for) != strings.end()

这会返回一个 bool(如果存在则为 true,否则为 false)

您还可以设置一个计数器,然后在遇到每个true 时将其递增。

【讨论】:

  • 谢谢,很遗憾,除了冒泡排序,我什么都不能用。
【解决方案4】:

这样做的一种方法是将所有子字符串保存到向量中,然后在向量上使用 std::count 函数并将结果放入映射中。这是示例代码

std::string s = "This is very good text and is really good to read";
        // Putting all substrings into a vector.. Need code to do that, for simplicity I am showing here manually
        vector<string> v1;
        v1.push_back("This");
        v1.push_back("is");
        v1.push_back("very");
        v1.push_back("good");
        v1.push_back("text");
        v1.push_back("and");
        v1.push_back("is");
        v1.push_back("rally");
        v1.push_back("good");
        v1.push_back("to");
        v1.push_back("read");
        // Map to create the result
        map<string, int> mp;
        for (auto v : v1) {
            size_t n = std::count(v1.begin(), v1.end(), v);
            mp[v] = n;
        }

        for (auto mvalue : mp) {
            cout << "String = " << mvalue.first.c_str() << "  Count Is " << mvalue.second << endl;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 2013-05-05
    相关资源
    最近更新 更多