When you have stored data inside a vector like that, how would you request all the names, titles and authors inside the vector, using cout?Code:struct data { string name; string title; string author; }; vector<data> books;
When you have stored data inside a vector like that, how would you request all the names, titles and authors inside the vector, using cout?Code:struct data { string name; string title; string author; }; vector<data> books;
use an iterator
Or use a loop.
Code:for(int i = 0; i < books.size(); i++){ std::cout<<books[i].name; //ETC }//for
Woop?
I wouldn't say it's better - in fact, I'd say it's disadvantageous when you can use indexes.
You would use an iterator like this:
Iterators become invalidated (invalid) if you perform certain operations on the container, such as resizing buffer or capacity.Code:for(std::vector<data>::iterator i = books.begin(); i != books.end();) { std::cout << *i++; }
Indexes never become invalid.
A loop is a control structure. An iterator is an object. In this case, the comparison is between using an index with a loop (prog-bman's example) or an iterator with a loop. It is also possible to use iterators with generic algorithms, but ignore that for now if you have not yet reached that stage in your learning.Is it better than a loop?
How do you use it in the example?Note that prog-bman's example is slightly inaccurate since the index is not of type int, but of type vector<data>::size_type, which is typically an unsigned int.Code:for (vector<data>::const_iterator i = books.begin(), end = books.end(); i != end; ++i) { std::cout << i->name; // etc }
That is not true: indices can become invalid when the container shrinks.Originally Posted by Elysia
Last edited by laserlight; 05-26-2008 at 12:44 AM.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Fine, fine
Code:for(std::vector<data>::size_type i = 0; i < books.size(); i++){ }//for
Woop?
Ah true, true. I never thought of that one.
Nevertheless, an iterator will also become invalid if the container shrinks beyond its position.
Iterators are a good idea, but the fact that they become invalid makes their usefulness drop. Thankfully, I have solved that issue in my own iterators.
I would say that it just makes them slightly more complicated to use.Iterators are a good idea, but the fact that they become invalid makes their usefulness drop.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)