Определение начальной позиции итератора

Рассмотрим векторный контейнер объектов C ++ с полями a и time. Мы хотим найти первый элемент в контейнере, который появляется после текущего времени (назовем его элементом N), а затем выполнить итерацию по контейнеру, начиная с первого элемента, который происходит в более раннее время, с полем a, имеющим определенное значение (так в основном из [N-1, инф)). Предполагая, что свойство не найдено, мы выполним вторую итерацию по всему списку.

Будет ли работать следующий код? (в примере мы хотим найти самый последний элемент с> = 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();
}

0

Решение

Двухступенчатый процесс. Сначала найдите поле после текущего времени:

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

Затем найдите элемент ДО afterCurrent с> = 5

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 к концу.

0

Другие решения


По вопросам рекламы ammmcru@yandex.ru
Adblock
detector