0

フィールド 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();
}
4

1 に答える 1

0

2 段階のプロセス。まず、現在時刻の後のフィールドを見つけます。

auto afterCurrent = std::find_if(myVectorObj.begin(), myVectorObj.end(), [=](const Field& field){
    return field.time >= currentTime;
});

afterCurrent次に、 >= 5 のBEFORE 要素を見つけます

auto reverse = myVectorType::const_reverse_iterator(afterCurrent);

auto atLeast5_rev = std::find_if(reverse, myVectorType.rend(), [=](const Field& field) {
    return field.a >= 5;
});

// convert back to forward iterator
auto atLeast5 = --(atLeast5_rev.base());

次に、最後まで繰り返しatLeast5ます。

于 2014-10-14T19:17:24.780 に答える