Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator in C language

Tags:

c

Has anyone tried providing support for Iterator in C. I am not looking for exact C++ STL::Iterator but minimal support for some idea to start would be good point for me .

I am developing container library same like stl but with minimal support, So I need this kind of functionality in those container.

I am looking forward of defining certain sets of algorithms interfaces ( similar to STL ). For example sort , which will take begin and end iterator and should work with any container.

like image 523
Avinash Avatar asked Feb 10 '11 19:02

Avinash


People also ask

Is iterator same as pointer?

An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualised as something similar to a pointer pointing to some location and we can access content at that particular location using them.

What are iterators used for?

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping.

What is the difference between iterator and loop?

In the absence of iterator calls, a loop statement simply executes an infinite loop. The difference between an iterator call and a routine call is that the iterator call "remembers" its state after it yields a value and, on subsequent calls, it simply resumes execution.

What is an iterator and its benefits?

Iterator is an interface that belongs to a collection framework. It allows you to traverse the collection, accesses the data element and removes the data elements of the collection.


1 Answers

Pointers can serve this function. container.begin() is easy, and container.end() doesn't take too much work.

Consider

Value array[N];
typedef Value* iterator;
iterator array_begin(Value a[]){ return &a[0];}
iterator array_end(Value a[], int n){ return &a[n];}
iterator array_next(iterator i) { return ++i;}

iterator it = array_begin(a);
iterator end = array_end(a,N);
for (;it < end; it=array_next(it))
{
    Value v = *it;
}

For other containers like lists, you can use NULL as end. Same for trees, but the next function needs to maintain state. (or the iterator is a pointer to a struct with state updated by calls to next(it)).

like image 66
AShelly Avatar answered Sep 29 '22 06:09

AShelly