C++ 为几乎相同的代码提供不同的输出

标签 c++ algorithm sorting quicksort

我把一本书的几行打乱了,他们的话也打乱了。我想使用快速排序算法对它们进行排序。我对线路进行了排序,效果很好。然后我尝试像这样对每一行进行排序;

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;
}

关于C++ 为几乎相同的代码提供不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40372865/

相关文章:

c++ - 采用 nulltpr_t : function definition does not declare parameters 的构造函数

c++ - 指向常量的指针的奇怪行为

algorithm - 分析 1 个可变寄存器指令集?

algorithm - 进行扑克游戏的伪代码

c++ - 如何在C++中初始化一个空整数数组

c++ - 功能级别的部分模板类特化

algorithm - 维护一组最小的子集

java - 排序数组 - 递归调用

javascript - 按特定顺序对数组进行排序

r - 当连续值缺失时,将向量排序为重复序列 R