【问题标题】:Compile Error with using lamda function with max_element使用带有 max_element 的 lambda 函数编译错误
【发布时间】:2019-05-08 16:18:48
【问题描述】:

我正在尝试编写一些代码来在轮廓的 std::vector 中找到具有最大尺寸的轮廓。

我有以下错误

error: conversion from ‘__gnu_cxx::__normal_iterator<std::vector<cv::Point_<int> >*, std::vector<std::vector<cv::Point_<int> > > >’ to non-scalar type
‘std::vector<cv::Point_<int> >::iterator {aka __gnu_cxx::__normal_iterator<cv::Point_<int>*, std::vector<cv::Point_<int> > >}’ requested
    std::vector<cv::Point2i>::iterator it = std::max_element(contours.begin(), contours.end()

下面是我的代码

std::vector<std::vector <cv::Point2i>> contours;
std::vector<cv::Vec4i> hierarchy;

cv::findContours(rImg, contours, hierarchy,CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, cv::Point(0, 0));
cv::Mat blank = cv::Mat::zeros(frame.size(), CV_8UC3);
cv::RNG rng;

std::vector<cv::Point2i>::iterator it = std::max_element(contours.begin(), contours.end(),
                                                        [](const std::vector<cv::Point2i>& p1, 
                                                        const std::vector<cv::Point2i>& p2)
                                                        { return p1.size()< p2.size(); });


std::vector<std::vector<cv::Point2i> > contourV;
contourV.push_back(it);

想知道哪里出了问题以及如何纠正它们

【问题讨论】:

  • 这就是为什么发明了关键字auto

标签: c++ algorithm iterator declaration


【解决方案1】:

您正在使用该类型的对象

std::vector<std::vector <cv::Point2i>> contours;

std::max_element算法中

所以迭代器应该对应于那个容器。那是

std::vector<std::vector <cv::Point2i>>::iterator it = std::max_element( /*...*/ );

或者写起来会更简单

auto it = std::max_element(contours.begin(), contours.end(),
                           [](const std::vector<cv::Point2i>& p1, 
                              const std::vector<cv::Point2i>& p2)
                              { return p1.size()< p2.size(); });

正如 @melpomene 在评论中指出的那样。

【讨论】:

  • 或者只是auto它。
  • 更简单:auto it = std::max_element(contours.begin(), contours.end(), [](const auto&amp; p1, const auto&amp; p2) { return p1.size() &lt; p2.size(); });
  • 感谢您的大力帮助....伙计们...刚开始在编程中使用 lamda 函数...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多