简体   繁体   中英

inner_product and complex vectors

It seems that I'm doing here something terribly wrong. Can you help me? The aim is to use inner_product for complex vectors.

#include<iostream>
#include<vector>
#include <numeric>
#include <complex>


using namespace std; 



template<class T>
complex< T > complex_prod(complex< T > a, complex< T > b)
{
 return conj<T>(a)*b; 
}

template<class T>
complex< T > add_c(complex< T > a, complex< T > b)
{
  return a+b;
}

int main()
{
  complex<double> c1(1.,3.);
  complex<double> c2(2.,4.);

  vector<complex<double> > C1(3,c1);
  vector<complex<double> > C2(3,c2);

 cout<<inner_product(C1.begin(),C2.end(),C2.begin(),0.,add_c<double>,complex_prod<double>) <<endl;

return 0;
}

I don't see why there is a conversion problem, everything seems to be defined and the iteration should make no problem.

The problem is that inner_product needs to know the type of the initial value, so you need to pass it an std::complex instead of a 0. :

inner_product(C1.begin(),C2.end(),C2.begin(),std::complex<double>(0.,0.),add_c<double>,complex_prod<double>);

or simply,

inner_product(C1.begin(),C2.end(),C2.begin(),std::complex<double>(),add_c<double>,complex_prod<double>);

Although an std::complex<double> can be implicitly constructed from a single numeric type

std::complex<double> c = 2.*4.*300;

the inner_product template looks like

template<
    class InputIterator1,
    class InputIteratorr2,
    class T,
    class BinaryOperation1,
    class BinaryOperation2
> T inner_product( InputIterator1 first1, InputIterator1 last1,
                   InputIterator2 first2, T value,
                   BinaryOperation1 op1,
                   BinaryOperation2 op2 );

so there is a template parameter for the value . So there is no way the compiler can know you mean std::complex<double> here, it just interprets 0. as double .

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