Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting complex numbers by their argument

I have a vector of complex numbers and I need to sort them by their argument. Sadly, the numbers have type complex<int>, so function arg(c) returns an integer in range [-3,3] instead of a float and the numbers can’t be sorted properly.

I’ve tried also

typedef complex<int> ci;
typedef complex<double> cd;

vector<ci> a;
sort(a.begin(), a.end(), [](ci v, ci u) { return arg(cd(v)) < arg(cd(u)); });

but it does not work either (compilation error: no matching function for call to ‘std::complex<double>::complex(ci&)).
Can I sort these numbers without changing their type?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You get the error because there is no converting constructor from std::complex<int> to std::complex<double> you have to construct the std::complex<double> by passing real and imaginary parts to the constructor:

#include <vector>
#include <complex>
#include <algorithm>

int main() {

    std::vector<std::complex<int>> a;
    std::sort(a.begin(), a.end(), [](const auto& v,const auto& u) {
        return std::arg(std::complex<double>(v.real(),v.imag())) < std::arg(std::complex<double>(u.real(),u.imag())); 
    });
}

Note that you can also use atan2 directly without constructing the std::complex<double> as mentioned by user17732522.

Last but not least, reconsider if you really need int with std::complex. From cppreference:

T – the type of the real and imaginary components. The behavior is unspecified (and may fail to compile) if T is not float, double, or long double and undefined if T is not NumericType.

Basically this means that you need to check the implementation you are using whether it supports std::complex<int> at all.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading