【问题标题】:Get the dot product of two vectors by functors and STL algorithms通过仿函数和STL算法得到两个向量的点积
【发布时间】:2012-10-30 03:05:08
【问题描述】:

我正在学习如何将仿函数与 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'|

【问题讨论】:

  • 没有问题。
  • 这是如何获得 +1 的?没有问题。
  • 是的。你忘了问一个问题。如果它没有按预期工作,请告诉我们结果如何与您的预期不同。如果有编译器错误,请告诉我们它是什么以及编译器突出显示的位置。如果您想对代码进行批评,那么 SO 不是正确的地方(也许可以尝试代码审查)
  • 一个问题需要至少一个问号。
  • 点积是 std::inner_product - sgi.com/tech/stl/inner_product.html

标签: c++ stl functor


【解决方案1】:

只需使用std::inner_product:

live demo

#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:

live demo

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

【讨论】:

  • 是的,这是一个很好的解决方案。但我不想使用 numeric.h 中提供的任何方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 2017-04-01
相关资源
最近更新 更多