【问题标题】:How to bind lambdas for STL algorithms to C style multidimensional arrays?如何将 STL 算法的 lambda 绑定到 C 风格的多维数组?
【发布时间】:2017-06-29 12:14:23
【问题描述】:

我一直在尝试使用STL 算法来处理多维数组的元素,但似乎没有任何东西可以绑定到它们。我该怎么做:

// Declaration of pix:
float pix[1000][2];

// (...)

const int sizeToParse = 300;
static auto colLessThan = [] 
    (const float coordPair_lhs[2], const float coordPair_rhs[2]) -> bool 
    // (const float** coordPair_lhs, const float** coordPair_rhs) -> bool 
    // (const float* coordPair_lhs[], const float* coordPair_rhs[]) -> bool 
{
    return coordPair_lhs[1] < coordPair_rhs[1]; 
};
float** lhsColMinIt;
float** lhsColMaxIt;
// float* lhsColMinIt[2];
// float* lhsColMaxIt[2];
std::tie(lhsColMinIt, lhsColMaxIt) = std::minmax_element(pix, pix + sizeToParse, colLessThan);

我的所有尝试都因编译器错误而被拒绝。

在接受答案后,它变成了这样:

在‘std::tuple<_t1 _t2>& std::tuple<_t1 _t2>::operator=(std::pair<_u1 _u2>&&) [with _U1 = const float ()[2]; _U2 = 常量浮点数 ()[2]; _T1 = 浮点数 (&)[2]; _T2 = float (&)[2]]':src/ClusterPairFunctions.cc:32:109: 从这里需要 /data/hunyadi/usr/include/c++/7.1.0/tuple:1252:25:错误:无效 从‘const float () [2]’到‘float ()[2]’的转换 [-fpermissive]

更新: 使用接受的答案提供的方法,代码可以工作,我只是未能解开编译器在std::tuple 中报告 const 不正确。

【问题讨论】:

  • 您能否详细说明您显示的代码存在的问题?它不会建立吗?你会崩溃吗?出乎意料的结果?还有什么?
  • 另外,请发布MVCE 以提供重现问题的机会。
  • 不知道更多(因为您没有我们显示编译器错误)我猜这与类型不匹配有关。 lambda 的参数是指向float(即float*)的指针,但数组pix 的元素是两个float数组,即输入float[2]。解决方案见the answer from Jarod42
  • 另一个问题(也由the answer from Jarod42 解决)是指向某个类型的指针的指针与该类型的数组数组相同。跨度>

标签: c++ multidimensional-array lambda stl-algorithm


【解决方案1】:

在 C++14 中,在 lambda 中使用 const auto&amp;

如果您必须明确提供类型:

static auto colLessThan = [] (const float (&lhs)[2], const float (&rhs)[2])
{
    return lhs[1] < rhs[1];
};

float (*lhsColMinIt)[2];
float (*lhsColMaxIt)[2];
std::tie(lhsColMinIt, lhsColMaxIt) =
    std::minmax_element(pix, pix + sizeToParse, colLessThan);

Demo

【讨论】:

  • 也许您可以详细说明您所做的更改,以及为什么您做出这些更改?
  • 我确认这确实有效,我的代码仍然拒绝用它编译:(
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
相关资源
最近更新 更多