【问题标题】:Sorting complex numbers in a vector c++在向量c ++中对复数进行排序
【发布时间】:2015-01-28 00:56:35
【问题描述】:

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

【问题讨论】:

  • 你做 cin>>cmplx,但 cmplx 是双精度数而不是复数。不要称你的矢量为矢量,即使它的工作原理令人困惑
  • 对复数排序?没那么容易,因为它们并没有真正定义的顺序。

标签: c++ sorting vector complex-numbers


【解决方案1】:

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

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

然后像这样调用排序:

sort(v.begin(), v.end(), complex_comparator&lt;double&gt;);

但是,我不太确定您要达到什么目标,因为说一个复数比另一个“大”是没有意义的。

【讨论】:

    【解决方案2】:

    std::sort 没有内置的复数排序函数,所以你必须编写自己的 比较器 函数并将其作为参数传递给sort() as

    sort(vector.begin(),vector.end(),myWay);
    

    myWay 函数定义为

    bool myWay(complex<double> a, complex<double> b)
    {
        if (real(a) == real(b))
            return imag(a) < imag(b);
        return real(a) < real(b);
    }
    

    所以,你的整个代码应该是这样的

    bool myWay(complex<double> a, complex<double> b)
    {
        if (real(a) == real(b)) //If real parts are equal
            return imag(a) < imag(b); //Sort by imaginary parts
        return real(a) < real(b); //If not, well, sort by real parts
    }
    main(){
      vector <complex<double> > vec; //Changed name from vector
      complex<double> cmplx;
      while ( cin >> cmplx ) //Use this to detect EOF
     {
        cout << "Enter a complex number or ctrl-d to stop" << endl;
        vec.push_back(cmplx);
     }
      sort(vec.begin(),vec.end(),myWay); 
      for (int x = 0; x < vec.size(); x++)
        cout << vec[x] << endl;
    }
    

    【讨论】:

    • 这并没有解决错误使用 eof 和 vectors 的笨拙名称冲突的(非常重要的)问题。此外,说您在排序中“调用”比较器函数是不正确的。你没有——你只是将它传递给排序,它会在适当的时候被调用。
    • 对不起,我会编辑那部分。感谢您的编辑。 :)
    • 感谢您的帮助!
    猜你喜欢
    • 2013-10-15
    • 1970-01-01
    • 2018-10-08
    • 2020-12-15
    • 1970-01-01
    • 2020-11-22
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多