Vector Iterator

Hi, im kinda new to C++ and im trying to understand what the vector iterator actually does, i dont get the meaning of it and dont see alot on the internet about it because it is all the same.. It does the same as a normal vector.. Can someone help me? Appreciate it!

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
std::vector<int> gameInt;

	for (int i = 0; i < 5; i++)
	{
		gameInt.push_back(i);
	}

	std::vector<int>::iterator iter;

	for (iter = gameInt.begin(); iter < gameInt.end(); iter++)
	{
		std::cout << *iter << std::endl;
	}
Last edited on
iterators are an abstraction of … iteration, really, pointer iteration (below). They make it so you can increment a thing one by one to touch the elements of it. Most (all?) of the stl containers have one, so while its easy to use an integer to iterate a vector, it is harder to do so with a list, for example. an iterator lets you iterate a list in a similar fashion, without having to know if it has pointers to next or any of that inside it, and if you change your vector to a list due to a design revision, the code isn't much different; if you used auto for the iterators, it may not even need to change.

pointer iteration:
char hw[] = "hello world";
char *iter = hw; //akin to .begin()
char *iter2 = &hw[12]; //akin to .end()
while(++iter < iter2)
{
cout << *iter;
}

they are absolutely redundant for vectors, and I seldom use them for vectors.
Last edited on
An iterator can be thought of as a pointer that "knows" how to iterate over a particular container, regardless of how that container is implemented internally (linked list, dynamic array, etc). This allows standard library algorithms to operate entirely on the iterator abstraction without requiring knowledge of the underlying container type.
Last edited on
Topic archived. No new replies allowed.