user1209304 user1209304 - 1 month ago 6
C++ Question

Calling conj() function on every element of a C++ complex vector

If I execute this code:

vector<complex<double> >
idft( vector<complex<double> > * v)
{

for_each(v->begin(), v->end(), conj);


then compiler gives me following error:

dft.cpp: In function 'std::vector<std::complex<double>, std::allocator<std::complex<double> > > idft(std::vector<std::complex<double>, std::allocator<std::complex<double> > >*)':
dft.cpp:38: error: no matching function for call to 'for_each(__gnu_cxx::__normal_iterator<std::complex<double>*, std::vector<std::complex<double>, std::allocator<std::complex<double> > > >, __gnu_cxx::__normal_iterator<std::complex<double>*, std::vector<std::complex<double>, std::allocator<std::complex<double> > > >, <unresolved overloaded function type>)'


If I apply conj() for just one element then it works fine:

vector<complex<double> >
idft( vector<complex<double> > * v)
{

conj(v->at(0));


How can I apply conj() for whole vector without using loop?

Answer

Edit From User The Quantum Physicist, until someone fixes this: This answer is wrong and will not modify your object and will actually NOT have any effect on anything.

for_each executes a function for every element but does not store the return value.


The problem seems to be that the compiler cannot find the appropriate instance of the std::conj method to call. In such cases you can enforce the following:

std::for_each(v->begin(), v->end(), std::conj<std::complex<double>>);

Hope that helps.