设置<Vec3b>的错误行为
Wrong behaviour of set<Vec3b>
我有一组Vec3b来保存可能的RGB像素值。
std::set<cv::Vec3b> used_colors;
但行为怪异:
used_colors.insert(cv::Vec3b(100, 255, 255));
// this returns 1 although (100, 0, 0) is NOT in the set
used_colors.count(cv::Vec3b(100, 0, 0));
找到值(100,0,0),因为其他以100开头的值已经插入到集合中。其他值如(80,0,0)找不到。这显然是错误的奇怪行为。
我实现了<像这样的比较运算符:
bool operator <(const cv::Vec3b &a, const cv::Vec3b &b) {
if(a[0] < b[0])
return true;
if(a[0] > b[0]);
return false;
if(a[1] < b[1])
return true;
if(a[1] > b[1]);
return false;
if(a[2] < b[2])
return true;
if(a[2] > b[2]);
return false;
return false;
}
您的operator<
由于几个if
语句后的错误分号而损坏。
考虑输入a = Vec3b(100, 255, 255)
和b = Vec3b(100, 0, 0)
。因为两者的R
值都是100
,所以测试结果是
if(a[0] > b[0]); // <-- notice the semicolon?
由于后面有分号,函数无条件返回false
。由于同样的原因,比较b < a
也返回false
;并且set::count
认为该元素已经存在。
去掉后面的分号,比较运算符就能正常工作了。
与其手动编写所有这些比较来进行字典排序,更简单、更不容易出错的方法是使用std::tie
bool operator<(const cv::Vec3b &a, const cv::Vec3b &b)
{
return std::tie(a[0], a[1], a[2]) < std::tie(b[0], b[1], b[2]);
}
比较函数填充了,可能是因为在一些if
语句之后有;
。
即使这样,这也比它需要的要复杂得多。std::tie
让它变成了一行:
bool operator <(const cv::Vec3b &a, const cv::Vec3b &b)
{
return std::tie(a[0], a[1], a[2]) < std::tie(b[0], b[1], b[2]);
}
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 设置<Vec3b>的错误行为