简体   繁体   中英

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

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> &lhs, const complex<T> &rhs) {
 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.

std::sort does not have a built-in function for sorting complex numbers, so you have to write your own comparator function and pass it as an argument in sort() as

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

The myWay function is defined as

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

So, your whole code should look like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM