对于几乎相同的代码,c++给出了不同的输出
C++ gives different outputs for almost the same code
我打乱了一本书的一些行,它们的单词也被打乱了。我想用快速排序算法对它们进行排序。我整理了台词,效果很好。然后我试着像这样对每一行进行排序;
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;
}
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 递归函数计算序列中的平方和(并输出过程)
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 输出类似于 FORTRAN 的无格式C++
- C++实现代码中的字符串不应存在于输出二进制文件中.如何解决
- 我需要转换一些代码,以便它适用于输入和输出文件文本
- 特定于域的语言工具 Visual Studio 2012 输出C++
- 物体相对于摄像机和视频的角度?视频和相机输出不同
- 设置输出格式以类似于C++中的表
- 将中值剪切颜色缩减算法的输出调色板应用于源图像
- 使用OpenCV校准了我的相机.如何将输出 xml 中的系数应用于我未来的项目
- 将效果应用于输出而不是位图
- 如何使用类似于gcc-xml的clang生成元数据输出
- 相当于c++中的printf()或格式化输出
- 对于几乎相同的代码,c++给出了不同的输出
- 如果你的程序在运行时几乎立即退出,如何确保控制台窗口保持打开状态以读取输出
- 实现[B,C]=f(A)语法(函数f作用于具有两个或多个输出数组的数组)
- 将facet应用于所有流输出,使用自定义字符串操作符
- 创建自己的输出存储而不是应用于现有存储的c++算法
- 输出到字符串的 cout 相当于什么?