考虑一个对象的 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();
}