[英]boost::lambda expression doesn't compile
我嘗試編寫一個函數,使用boost lambda庫計算兩個代碼字之間的漢明距離。 我有以下代碼:
#include <iostream>
#include <numeric>
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/if.hpp>
#include <boost/bind.hpp>
#include <boost/array.hpp>
template<typename Container>
int hammingDistance(Container & a, Container & b) {
return std::inner_product(
a.begin(),
a.end(),
b.begin(),
(_1 + _2),
boost::lambda::if_then_else_return(_1 != _2, 1, 0)
);
}
int main() {
boost::array<int, 3> a = {1, 0, 1}, b = {0, 1, 1};
std::cout << hammingDistance(a, b) << std::endl;
}
而我得到的錯誤是:
HammingDistance.cpp: In function ‘int hammingDistance(Container&, Container&)’:
HammingDistance.cpp:15: error: no match for ‘operator+’ in ‘<unnamed>::_1 + <unnamed>::_2’
HammingDistance.cpp:17: error: no match for ‘operator!=’ in ‘<unnamed>::_1 != <unnamed>::_2’
/usr/include/c++/4.3/boost/function/function_base.hpp:757: note: candidates are: bool boost::operator!=(boost::detail::function::useless_clear_type*, const boost::function_base&)
/usr/include/c++/4.3/boost/function/function_base.hpp:745: note: bool boost::operator!=(const boost::function_base&, boost::detail::function::useless_clear_type*)
這是我第一次玩boost lambda。 請告訴我哪里出錯了。 謝謝。
編輯:
非常感謝! 這是工作代碼(僅供參考):
#include <iostream>
#include <numeric>
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/if.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/array.hpp>
using boost::lambda::_1;
using boost::lambda::_2;
template<typename Container>
int hammingDistance(Container & a, Container & b) {
return std::inner_product(
a.begin(),
a.end(),
b.begin(),
0,
(_1 + _2),
boost::lambda::if_then_else_return(_1 != _2, 1, 0)
);
}
int main() {
boost::array<int, 3> a = {1, 0, 1}, b = {0, 1, 1};
std::cout << hammingDistance(a, b) << std::endl;
}
第一個問題:當使用boost/lambda
,包括<boost/lambda/bind.hpp>
而不是<boost/bind.hpp>
第二個問題:在#includes之后需要using namespace boost::lambda
仍然不編譯
編輯:
第三個問題 - 你需要為std::inner_product
6個參數,你缺少一個初始化參數。 可能會添加0
作為第四個參數。
我可能錯了,但我認為你應該using namespace boost::lambda;
在您的函數之前,占位符(_1,_2等)位於該命名空間中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.