【问题标题】:I need this simple repeated words detector explained [closed]我需要解释这个简单的重复单词检测器[关闭]
【发布时间】:2012-10-10 17:14:46
【问题描述】:

代码完美运行,但我对它的工作原理感到困惑。我完全不明白为什么我们需要对字符串向量进行排序。它只会按字母顺序对单词进行排序,对吗?另外,当我们将它与字符串变量“Previous”进行比较时,它如何检测任何单词而不仅仅是相邻的单词

#include <iostream>
#include <vector>

using namespace std;

void detect(vector<string> vs);

int main() {
vector<string> vs;
string current;
while (cin>>current)
    vs.push_back(current);
    sort(vs.begin(), vs.end());
    detect (vs);
    system("pause");
}

void detect(vector<string> vs){
    string previous = " ";
    int index = 0;
    while (index < vs.size()) {
        if (vs[index]==previous) {
            cout<<"repeated words: " <<previous<< endl;
        }
        previous = vs[index];
        index++;
    }
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    由于向量是使用sort() 按字母顺序排序的,因此任何重复的单词都将彼此相邻(因为它们是同一个单词并且会在排序中竞争相同的位置)。这样detect() 就可以查看所有相邻单词对并以这种方式检测重复项。如果向量未排序,则detect() 将不起作用。

    【讨论】:

      【解决方案2】:

      Answer1:如果按字母顺序排序,任何相等的元素都将相邻。

      Answer2:它确实只得到彼此相邻的相等值,但由于排序,所有相等的值都将彼此相邻。

      我希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2012-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-18
        相关资源
        最近更新 更多