【问题标题】:C++ gives different outputs for almost the same codeC++ 为几乎相同的代码提供不同的输出
【发布时间】:2017-03-15 08:20:19
【问题描述】:

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

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

【问题讨论】:

  • 对不起,我没有理解,编译器特定扩展是什么意思?如果这就是你的意思,我正在使用 Visual Studio。
  • 你在用什么 rand() ?
  • 对我来说这毫无意义:It gives an output as I didn't call the quicksort function 当然它给出了输出。能否详细说明。还有It is the same code with one line missing ....那么它不是相同的代码。请解释一下。
  • @4386427 MSVC 扩展,所以技术上不,这不是 C++。建议交换基于:for (Line &amp; l: lines) 的 C++11 范围以符合标准。
  • 我不知道 for each 扩展,因为它不是 C++。我的猜测是l 成为局部变量,因此在循环完成时对其所做的任何更改都会丢失。试试这个:for (auto&amp; l : lines)

标签: c++ algorithm sorting quicksort


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2013-12-09
    • 2019-02-13
    相关资源
    最近更新 更多