Monday, May 24, 2010

Why should I use iterators rather than int for traversing through a list in C++.?

Why should I use


____________________


using namespace std;





vector%26lt;int%26gt; myIntVector;


vector%26lt;int%26gt;::iterator myIntVectorIterator;





// Add some elements to myIntVector


myIntVector.push_back(1);


myIntVector.push_back(4);


myIntVector.push_back(8);





for(myIntVectorIterator = myIntVector.begin();


myIntVectorIterator != myIntVector.end();


myIntVectorIterator++)


{


cout%26lt;%26lt;*myIntVectorIterator%26lt;%26lt;" ";


//Should output 1 4 8


}











Rather than


____________________





using namespace std;





vector%26lt;int%26gt; myIntVector;


// Add some elements to myIntVector


myIntVector.push_back(1);


myIntVector.push_back(4);


myIntVector.push_back(8);





for(int y=0; y%26lt;myIntVector.size(); y++)


{


cout%26lt;%26lt;myIntVector[y]%26lt;%26lt;" ";


//Should output 1 4 8


}

Why should I use iterators rather than int for traversing through a list in C++.?
Hi





well iterator have a main function, to access data from a container. when you have an stack, queue or some special container from STL you must use iterator to access the data inside those structure. It is impossible or very difficult to use other thing.





It is best practice to learn how to use iterator when you are dealing with complex data structures. Here i put some links.





good luck
Reply:safety, for one

flower girl

No comments:

Post a Comment