查找下限的返回值
finding the return value of the lower_bound
我正在尝试使用lower_bound来确定值是否在指向结构的指针向量中。我正在使用
auto it = lower_bound( myVector.begin() , myVector.end() , value , comparer() );
comparer函数看起来像
struct comparer
{
bool operator ()(Property * ms, int const i) const
{
return ms -> ID < i;
};
};
我想检查是否找到了具有所述ID的元素。我该怎么查?我试过使用
if( (*it) -> ID == value ) {
return false;
}
但这是抛出分段错误,有没有办法检查元素是否已经存在?
如果您只想检查对象是否存在,请使用std::binary_search
:
bool exists = std::binary_search(myVector.begin(), myVector.end(), value, comparer());
也就是说,如果你想要迭代器,你不仅需要检查值是否匹配,还必须先检查是否得到了除结束迭代器之外的东西:
auto it = std::lower_bound(myVector.begin(), myVector.end(), value, comparer());
if (it != myVector.end() && (*it)->ID == value) {
return false;
}
如果您确实得到了end()
,那么取消引用是未定义的行为,这可能表现为分段错误。
相关文章:
- 从python中调用C++函数并获取返回值
- 为什么模板类中的对象不能返回值
- 返回值优化:显式移动还是隐式
- lock_guard是否保护返回值
- 调用CreateProcess()并获取字符串的返回值
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 查找 GCD:并非所有控制路径都返回值
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 如何从 std::thread 返回值
- 将返回值从 exe 传递到 bat,并将其传递给 C# 中的进程
- 方法错误"not all control paths return a value"和方法不返回值
- 如何读取 C++ SAFEARRAY**,该 SAFEARRAY** 是 COM 互操作的结果,其中 C# 返回值为
- 对fread的返回值感到困惑
- 程序不向函数返回值
- 查找下限的返回值
- 通过 unique_ptr 的向量搜索的查找函数的返回值
- 低内存内存管理:查找和跟踪随机函数返回值的重复项
- 查找失败时增强string_algo返回值