在向量c ++中对复数进行排序

use*_*550 2 c++ sorting vector complex-numbers

我是c ++和编程的新手,我试图将用户输入的复数输入单独的行,直到用户点击ctr-d.我的逻辑是否正确?我知道我有很多错误.提前致谢

main(){
  vector <complex<double> > vector;
  double cmplx;
  while (!cin.eof()){
    cout << "Enter a complex number or ctr-d to stop" << endl;
    cin >> cmplx;
    vector.push_back(cmplx);
  }
  sort(vector.begin(),vector.end());
  for (int x = 0; x < vector.size(); x++)
    cout << vector[x] << endl;
}
Run Code Online (Sandbox Code Playgroud)

nic*_*yte 6

从数学上讲,没有为复数定义排序,这就是没有operator<定义的原因complex.您可以尝试发明自己的排序函数(例如按字典顺序排序),但这需要编写自己的比较器函数:

template <class T>
bool complex_comparator(const complex<T> &lhs, const complex<T> &rhs) {
 return real(a) == real(b) ? imag(a) < imag(b) : real(a) < real(b);
}
Run Code Online (Sandbox Code Playgroud)

然后调用这样的排序:

sort(v.begin(), v.end(), complex_comparator<double>);

但是,我不太确定你想要实现什么,因为没有任何意义可以说一个复数比另一个复杂.