Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting complex numbers in a vector c++

Im new to c++ and programming and I am attempting to take complex numbers entered by the user on separate lines until the user hits ctr-d. Is my logic on the right track? I know I have many errors. Thanks in advance

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;
}
like image 795
user3602550 Avatar asked Sep 10 '26 06:09

user3602550


1 Answers

Mathematically speaking, there is no ordering defined for complex numbers, which is why there is no operator< defined for complex. You can try inventing your own ordering function (such as ordering them lexicographically) but that requires writing your own comparator function:

template <class T>
bool complex_comparator(const complex<T> &a, const complex<T> &b) {
    return real(a) == real(b) ? imag(a) < imag(b) : real(a) < real(b);
}

and then calling sort like this:

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

However, I'm not quite sure what you're trying to achieve because there is no sense in saying that one complex number is "bigger" than another.

like image 191
nicebyte Avatar answered Sep 12 '26 19:09

nicebyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!