フィールド a と time を持つ、オブジェクトの C++ ベクトル コンテナーを考えてみましょう。現在の時間以降に発生するコンテナー内の最初のアイテムを見つけて (アイテム N と呼びましょう)、特定の値を持つフィールド a を使用して、以前に発生した最初のアイテムからコンテナーを反復処理します (したがって、基本的に、[N-1, inf)) から。プロパティが見つからないと仮定すると、リスト全体に対して 2 回目の反復を実行します。
次のコードは機能しますか? (例では、 >= 5 の最新のアイテムを見つけたいと考えています)。これを行うより良い方法はありますか?
myVectorType::const_iterator cBegin = myVectorObj.begin();
myVectorType::const_iterator cEnd = myVectorObj.end();
// Find the most recent item with a >= 5
for (myVectorObj::const_iterator iter = cBegin; iter != cEnd; ++iter)
{
if ((*iter).time >= currentTime)
{
// Found an item that is in the future - we should have determined the location of the most
// recent item with the propery we're looking for.
break;
}
else if ((*iter).a >= 5)
{
// Past item with a >= 5. Save the location.
cBegin = iter;
}
}
// Iterate over the container, beginning at the most recent item with a >= 5, if it was found.
for (; cBegin != cEnd; ++cBegin)
{
dostuff();
}