查找下限的返回值

finding the return value of the lower_bound

本文关键字:返回值 查找      更新时间:2023-10-16

我正在尝试使用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(),那么取消引用是未定义的行为,这可能表现为分段错误。