-1

値が構造体へのポインターのベクトル内にあるかどうかを調べるために、lower_bound を使用しようとしています。私は使っている

auto it = lower_bound( myVector.begin() , myVector.end() , value , comparer() );

比較関数は次のようになります

struct comparer
{
    bool operator ()(Property * ms, int const i) const
    {
        return ms -> ID  < i;
    };
};

上記のIDを持つ要素が見つかったかどうかを確認したい。どうすれば確認できますか?使ってみた

if( (*it) -> ID == value ) {
   return false;
}

しかし、これはセグメンテーション違反をスローしています。要素が既に存在するかどうかを確認する方法はありますか?

4

1 に答える 1

3

オブジェクトが存在するかどうかを確認するだけの場合は、次を使用し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()、その逆参照は未定義の動作であり、セグメンテーション違反として現れる可能性があります。

于 2016-03-30T18:10:28.070 に答える