0

考虑一个对象的 C++ 向量容器,其中包含字段 a 和时间。我们想找到容器中在当前时间之后出现的第一个项目(我们称之为项目 N),然后从较早时间出现的第一个项目开始迭代容器,其中字段 a 具有一定的值(所以基本上,来自 [N-1, inf))。假设未找到该属性,我们将对整个列表执行第二次迭代。

下面的代码会起作用吗?(在示例中,我们希望找到 a >= 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

两步过程。首先,找到当前时间之后的字段:

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 回答