В стандартной библиотеке C нет итераций по типу коллекции, кроме как что-то вроде strtok()
, которое будет перебирать текстовую строку с использованием предоставленного шаблона идентификации токена.
Однако есть функция bsearch()
, которая выполняет поиск по отсортированному списку элементов и не совсем то, что вам нужно.
Звучит так, будто вы хотите что-то вроде следующего. Это демонстрирует реализацию алгоритма, однако я не уверен, как выглядят данные временных точек, так что это то, что вам нужно будет предоставить.
typedef unsigned long long TimePoint; // made up time data item
typedef struct {
int bFound;
unsigned long ulCurOffset; // array position where item found if bFound is true.
unsigned long ulOffset; // next array position to test
unsigned long ulCount; // count of times found
} IteratorThing;
IteratorThing IterateFunc (IteratorThing x, TimePoint *array, size_t len, TimePoint search)
{
x.bFound = 0; // assume we didn't find one.
// resuming from the current place in the array, search until we
// find a match or we reach the end of the array.
for ( ; x.ulOffset < len; x.ulOffset++) {
// this is a simple comparison for equality which may need to be
// more complex for your specific application.
if (array[x.ulOffset] == search) {
// we have found a match so lets update counts, etc.
x.ulCount++; // count of this search item found.
x.bFound = 1; // indicate we found one.
x.ulCurOffset = x.ulOffset; // remember where we found it.
x.ulOffset++; // point to the next array item to look at
break;
}
}
return x;
}
Это будет использоваться как в:
void main_xfun(void)
{
TimePoint array[] = { 1, 2, 3, 2, 3, 4, 0 };
TimePoint search = 2;
size_t len = sizeof(array) / sizeof(array[0]);
{
IteratorThing x = { 0 }; // define and initialize our iterator
while ((x = IterateFunc(x, array, len, search)).bFound) {
// do what is needed when we find a time value
// array offset to the item is x.ulCurOffset
// current count of times found is in x.ulCount;
printf(" found item %d at offset %d count is %d\n", (long)array[x.ulCurOffset], x.ulCurOffset, x.ulCount);
}
printf(" item %d found %d time\n", (long)search, x.ulCount);
}
{
IteratorThing x = { 0 }; // define and initialize our iterator
search = 25;
while ((x = IterateFunc(x, array, len, search)).bFound) {
// do what is needed when we find a time value
// array offset to the item is x.ulCurOffset
// current count of times found is in x.ulCount;
printf(" found item %d at offset %d count is %d\n", (long)array[x.ulCurOffset], x.ulCurOffset, x.ulCount);
}
printf(" item %d found %d time\n", (long)search, x.ulCount);
}
}
производит вывод
found item 2 at offset 1 count is 1
found item 2 at offset 3 count is 2
item 2 found 2 time
item 25 found 0 time
Чтобы возобновить поиск с самого начала, просто инициализируйте структуру итератора для всех нулей.
Что было бы действительно интересно, так это предоставить указатель на функцию сравнения в интерфейсе функции IterateFunc()
, которая будет вызываться для сравнения. Это было бы в соответствии с функцией bsearch()
, для которой требуется указатель на функцию сравнения, но это, вероятно, излишне для ваших конкретных потребностей.