簡體   English   中英

通過函子和STL算法得到兩個向量的點積

[英]Get the dot product of two vectors by functors and STL algorithms

我正在學習如何使用函子和 STL 算法來計算兩個向量的點積。 這是我的代碼:

template<size_t DIM>
double Vector<DIM>::operator*(const Vector<DIM>& rhs) const {
    double dotPro = 0;
    std::for_each(vec, vec + DIM, std::bind2nd(dot_product<double>(rhs.get()), dotPro));
    return dotPro;
}
/*vec is a double array and the data member of Vector class. I want to get the 
dot product of rhs and *this by using std::for_each(). 
rhs.get()returns a const double* which is the start address of rhs's vec*/

/*The codes below define the functor.  dotPro is passed as a reference so as to 
it could be save the last result.*/  
template<typename T>
struct dot_product: public std::binary_function<T, T, void> {
    const T* arg;
    sum(const T* dbl) : arg(dbl){};
     void operator() (const T dbl, T& dotPro) {
        dotPro += *arg++ * dbl;
    }
};

對不起,我忘記了我的問題......問題是我的代碼無法編譯。 這是編譯錯誤:

error: no match for call to '(const dot_product<double>) (const double&, const double&)'|
note: candidates are: void dot_product<T>::operator()(T, T&) [with T = double]|

這里是 binders.h 中發生的錯誤

c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\include\c++\backward\binders.h|147|error: return-statement with a value, in function returning 'void'|

只需使用std::inner_product

現場演示

#include <algorithm>
#include <iostream>
#include <iterator>
#include <ostream>
#include <numeric>
#include <cstdlib>
#include <vector>

using namespace std;

int main()
{
    vector<int> v1,v2;
    generate_n( back_inserter(v1), 256, rand );
    generate_n( back_inserter(v2), v1.size(), rand );
    cout << inner_product( v1.begin(), v1.end(), v2.begin(), 0 ) << endl;
}

是的,這是一個很好的解決方案。 但我不想使用 numeric.h 中提供的任何方法。

只需定義您自己的 dot_product:

現場演示

template<typename InputIterator1,typename InputIterator2,typename ValueType>
ValueType dot_product( InputIterator1 first, InputIterator1 last, InputIterator2 another, ValueType init)
{
    while(first!=last)
    {
        init += (*first) * (*another) ;
        ++first;
        ++another;
    }
    return init;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM