对于几乎相同的代码,c++给出了不同的输出

C++ gives different outputs for almost the same code

本文关键字:输出 于几乎 代码 c++      更新时间:2023-10-16

我打乱了一本书的一些行,它们的单词也被打乱了。我想用快速排序算法对它们进行排序。我整理了台词,效果很好。然后我试着像这样对每一行进行排序;

for each (Line l in lines) {
    srand(255);
    l.quicksort(0, l.words.size() - 1);
    for each (Word w in l.words)
        cout << w.content << " ";
    cout << endl;
}

srand部分是因为我使用了随机化快速排序。这个循环给出了正确的结果。然而,当我试着像这样再写一遍的时候;

for each (Line l in lines) {
    for each (Word w in l.words)
        cout << w.content << " ";
    cout << endl;
}

它给出的输出就像我没有调用快速排序函数。它是相同的代码,只是少了一行。为什么会发生这种情况?

类行:

#include<iostream>
#include<vector>
#include "word.h"
using namespace std;
class Line {
public:
    vector<Word> words;
    Line(string&, string&);
    void quicksort(int, int);
private:
    int partition(int, int);
    void swap(int, int);
};
Line::Line(string& _words, string& orders) {
    // Reading words and orders, it works well.
}
void Line::quicksort(int p, int r) {
    if (p < r) {
        int q = partition(p, r);
        quicksort(p, q - 1);
        quicksort(q + 1, r);
    }
}
int Line::partition(int p, int r) {
    int random = rand() % (r - p + 1) + p;
    swap(r, random);
    int x = words[r].order;
    int i = p - 1;
    for (int j = p; j < r; j++)
        if (words[j].order <= x) {
            i++;
            swap(i, j);
        }
    swap(i + 1, r);
    return i + 1;
}
void Line::swap(int i, int j) {
    if (i != j) {
        Word temp = words[j];
        words[j] = words[i];
        words[i] = temp;
    }
}

您对本地副本进行排序,而不是通过引用进行迭代:

srand(255); // Call it only once (probably in main)
for (Line& l : lines) {
    l.quicksort(0, l.words.size() - 1);
    for (const Word& w : l.words)
        std::cout << w.content << " ";
    std::cout << std::endl;
}
// Second loop
for (const Line& l : lines) {
    for (const Word& w : l.words)
        std::cout << w.content << " ";
    std::cout << std::endl;
}