gpt4 book ai didi

c++ - boost::lambda 表达式无法编译

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:40:47 25 4
gpt4 key购买 nike

我尝试使用 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>

第二个问题:你需要一个using namespace boost::lambda在#includes

之后

虽然仍然没有编译


编辑:
第三个问题 - std::inner_product 需要 6 个参数,您缺少初始化参数。可能添加 0作为第四个参数。

关于c++ - boost::lambda 表达式无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2559246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com