I have read plenty of times about iterators or constant iterators. What does their name mean and what do they do?
I understand they have something to do with memory manipulation but no matter how much code i read, i just can't get their meaning!!
Printable View
I have read plenty of times about iterators or constant iterators. What does their name mean and what do they do?
I understand they have something to do with memory manipulation but no matter how much code i read, i just can't get their meaning!!
The concept of an iterator generalises the concept of a pointer, and in fact pointers are random access iterators. When you see const_iterator, it means "iterator to const" rather than "iterator that is const". Among other things, they allow certain generic algorithms to be separated from containers: the user provides iterators to the algorithm to denote a range within the container (or otherwise), and the algorithm can require certain categories of iterators to work (i.e., some iterators are more powerful than others).Quote:
Originally Posted by Sipher
well, an iterator is an object that allows a programmer to traverse through all
the elements of a collection (like std:: ), regardless of its specific implementation.
So, you're saying that iterators are useful for developing DLLs and the like?
Is an iterator just an shared interface or something more?
(I don't know if i understood what you said laserlight, i have to brush up my english)
Not really. An iterator is an abstract way of representing something that can step through the elements of a container. A container is something like an array, list, map, vector, set, etc. An iterator is something that allows you to step through each element in that container. For example, let's say you have a list:Then you add the numbers 1 - 5 to the list:Code:std::list<int> list_of_numbers;
Later on you want to go through each number in the list and add them all up. To do that, you could use an iterator to step through them one at a time and add them to the sum:Code:for (int i = 1; i <= 5; ++i)
list_of_numbers.push_back(i);
In this case it would output 15, since 1 + 2 + 3 + 4 + 5 = 15.Code:int sum = 0;
// Create a new iterator and point to the beginning of the list:
std::list<int>::iterator current_element = list_of_numbers.begin();
// Loop while the iterator doesn't point to the end of the list
while (current_element != list_of_numbers.end())
{
// Use * to get the value at that point in the list. Add the value to the sum:
sum += *current_element;
// Increment the iterator to the next element in the list:
++current_element;
}
std::cout << "The sum is " << sum << ".\n";
A const_iterator just means you promise not to change the values in the container, so you could have (and should have) made current_element a std::list<int>::const_iterator in the previous example.
Oh, now i got it!! Thanks for the quick reply guys!