为什么无错误的代码不能在一台机器上给出预期的结果,而在另一台机器上是的

时间:2012-06-13 14:16:33

标签: c++ sorting

我遇到了部分代码问题。它应该工作,因为它没有错误,并且没有逻辑问题,因为它可以在其他人的PC上工作,但在我的计算机上,结果与输入相同。 代码(可运行):

#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
class RAngle{
public:
   int x,y,l;
   RAngle(){}
   RAngle(int i,int j,int k){
      x=i,y=j,l=k;
   }
   bool operator<(const RAngle& rhs)const{
      if(l < rhs.l){
         return true;
        }
      return 0;
  }
  friend ostream& operator << (ostream& out, const RAngle& ra){
    out << ra.x << " " << ra.y << " " << ra.l;
    return out;
  }
  friend istream& operator >>( istream& is, RAngle &ra){
    is >> ra.x;
    is >> ra.y;
    is >> ra.l;
    return is ;
  }
};
void descrSort(vector <RAngle> &l){
    for(unsigned i=0; i<l.size();i++){
        cout<<l[i]<<endl;
    }
    cout << "==================" << endl;
    sort(l.begin(),l.end());
    reverse(l.begin(),l.end());
    for(unsigned i=0; i<l.size();i++){
        cout<<l[i]<<endl;
    }
}
void readData(vector <RAngle> &l){
   RAngle r;
   ifstream f_in;
   f_in.open("test.txt",ios::in);
   for(int i=0;i<10;++i){
      f_in >> r;
      l.push_back(r);
   }
}
int main(){
   vector <RAngle> a;
   readData(a);
   descrSort(a);

   return 0;
  }

DATA:

1 7 31
2 2 2
3 3 3
4 5 1
10 5 1
1 1 9
10 3 10
4 5 7
5 4 15
2 3 25
1 7 31

其他机器上的输出(只有打印部件,descr排序):

1 7 31
2 3 25
5 4 15
10 3 10
1 1 9
4 5 7
3 3 3
2 2 2
10 5 1
4 5 1
我的电脑上的

(hoel输出):

1 7 31

2 2 2

3 3 3

4 5 1

10 5 1

1 1 9

10 3 10

4 5 7

5 4 15

2 3 25

==================
1 7 31

2 2 2

3 3 3

4 5 1

10 5 1

1 1 9

10 3 10

4 5 7

5 4 15

2 3 25

2 个答案:

答案 0 :(得分:1)

这意味着您的代码有错误。 C和C ++允许编译和运行实际上有错误的东西。像这样:

int i;
std::cout << i << std::endl;

将在不同的机器上做不同的事情。我称之为错误。编译器不会。

现在,对于错误的位置,这是我的“使用调试器”语音。使用调试器。这将花费你更少的时间来使用调试器,并且有很大的机会找到错误,而不是我读取你的代码以查看是否有任何跳出来。使用-g进行编译。谷歌“gdb备忘单”。用gdb运行。按照备忘单。查看代码执行意外操作的位置。

在提供错误输出的机器上执行此操作似乎很聪明。并看看它在哪里做错了。

答案 1 :(得分:0)

要扩展@djechlin所说的内容,你最有可能的是“未定义的行为”。

大多数编程语言严格定义可以做什么和不可以做什么,编译器编写者使用它来生成编译器错误。另一方面,未定义的行为意味着它取决于编译器编写器和系统;任何事情都可能发生 - 它可以正常工作,它可以消除你的引导扇区,僵尸阿兰图灵上升和你的大脑盛宴等。

例如,使用未初始化的变量,如:

int i; 
std::cout << i << std::endl; 
某些编译器上的

会在调试版本中为您提供类似0xCECECECE的模式,以帮助查找未初始化的变量。在发布版本中,编译器可能将其设置为0,或者它可能是垃圾数据。