help with iterators?

im having a problem understanding what they do and how to use them. can anybody help?

iterators are kind of array index's but point to contrainers. so if you do this:

1
2
3
char arr[10] = "abcd";
for(int i = 0; i < 10; i++)
    printf("%c", arr[i]);               //i is used to point to each index of the array. 



similarly, iterators are indexes for containers. so if we do this:

1
2
3
4
5
6
7
8
std::vector<char> vec_int;
vec_int.push_back('a');
vec_int.push_back('b');

std::vector<char>::iterator vec_int_iter;
vec_int_iter = vec_int.begin();
for(; vec_int_iter != vec_int.end(); vec_int_iter++)
	printf("%c", *vec_int_iter);



as iterators are pointers, so to see the value you have to deference them.



Suppose you have an array of ints. You've put some values in it and
now you want to print them. What will you do? You'll use a for loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
    int my_array[5] = { 5, 4, 3, 2, 1 };

    int i;

    for (i = 0; i != 5; ++i)
        std::cout << my_array[i] << std::endl;

    return 0;
}

Easy, right? Well, it's easy because the elements of an array occupy contiguous memory locations.
There are many cases, though, where an array is not a good choice to store your data. You need
the advanced functionality provided by the complex data structure X. However, X doesn't store its
elements in contiguous memory locations, because it's inefficient. How will you iterate over these
elements, then? That's exactly the problem iterators solve:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <list>

int main()
{
    std::list<int> my_list;

    my_list.push_back(5);
    my_list.push_back(4);
    my_list.push_back(3);
    my_list.push_back(2);
    my_list.push_back(1);

    std::list<int>::const_iterator it;

    for (it = my_list.begin(); it != my_list.end(); ++it)
        std::cout << *it << std::endl;

    return 0;
}

aah.. our post's clashed.... we got the same example. :)
That's ok. He'll learn better this way :D
this helped me too thanks for taking the time to post the examples
Topic archived. No new replies allowed.