-8

该代码完美运行,但我对它的工作原理感到困惑。我完全不明白为什么我们需要对字符串向量进行排序。它只会按字母顺序对单词进行排序,对吗?此外,当我们将它与字符串变量“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++;
    }
}
4

2 回答 2

2

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

于 2012-10-10T17:18:52.360 回答
1

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

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

我希望这有帮助。

于 2012-10-10T17:31:04.527 回答