سؤال

حاولت أن أكتب وظيفة تحسب مسافة الهامغ بين مجموعتين من الترميز باستخدام مكتبة 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

لا يزال لا يجمع رغم ذلك


تعديل:
المشكلة الثالثة - تحتاج 6 حجج لـ std::inner_product, ، أنت تفتقد حجة التهيئة. ربما إضافة 0 كحجة فرعية.

نصائح أخرى

قد أكون مخطئًا ولكني أعتقد أنه يجب أن يكون لديك using namespace boost::lambda; قبل وظيفتك باعتبارها العناصر النائبة (_1 ، _2 إلخ) في مساحة الاسم.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top