|
-
January 19th, 2011, 07:54 AM
#1
C++ iterator
I was meaning to understand in C++ what are iterator , I have gone through whats on the web , however still did not get it. could someone please provide explanation , with some example ,
I have always found , seeing an example helps me better than just plain words.
-
January 19th, 2011, 08:55 AM
#2
Re: C++ iterator
An iterator object is associated to a container so that it points to one element of that container or to an invalid pseudo element which signals the end of the iteration. The iterator provides a function 'next' - mostly via the ++ operator - which makes the iterator object pointing to the next element.
Code:
// the container
std::vector<int> cont;
cont.push_back(1);
cont.push_back(2);
// the iterator (pointing to nowhere and not yet associated to the container)
std::vector<int>::iterator iter;
for (iter = cont.begin(); // now iter is associated to the container and points to first element
iter !=cont.end(); // and runs until the iter is end iterator of the container
++iter) // points to next element after each cycle
{
int i = *iter; // get value of element from iterator by dereferencing (it is 1 or 2)
std::cout << i << std::endl;
}
-
January 19th, 2011, 06:19 PM
#3
Re: C++ iterator
thank you , except for the obvious , as looping through the container , what are there practical uses.
-
January 19th, 2011, 06:34 PM
#4
Re: C++ iterator
 Originally Posted by aamir121a
thank you , except for the obvious , as looping through the container , what are there practical uses.
Well, looping through a container seems to be a very practical use to me, especially for a container such as a std::list or std::map that can't be simply indexed like a vector can.
Due to their ability to make any kind of container "look the same", iterators are also used in almost every STL algorithm such as std::transform() as a generic way to specify data without caring where it's stored.
-
January 19th, 2011, 11:28 PM
#5
Re: C++ iterator
thanks again much appreciated
-
January 20th, 2011, 04:18 AM
#6
Re: C++ iterator
Custom iterators can also be useful when you want to iterate from something other than 'first to last'. Many standard containers have a reverse iterator, where incrementing will step backwards through the container. This means that only one algorithm need be written which assumes the availability of a ++ operator in the iterator. It's up to the iterator to define what ++ actually does.
"It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
Richard P. Feynman
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|