Im just starting to learn about vectors and I cannot grasp the concept of iterators and const interators and what they do. How do they work? Ive read the section in the book over and over again and tried practice problems and I just dont understand
#include <iostream>
#include <list>
usingnamespace std;
template <typename Iterator>
void print( Iterator begin, Iterator end )
{
while (begin != end)
{
cout << *begin;
++begin;
cout << "\n"; // Yeah, I moved this into the loop
}
}
int main()
{
list <constchar*> names;
names.push_back( "Malcolm" );
names.push_back( "Zoe" );
names.push_back( "Kaylee" );
names.push_back( "Jayne" );
// and so on...
// Now we can iterate through the list with our handy pointer-like syntax
print( names.begin(), names.end() );
}
Hmmm that helps but how does an interator know what vector to go through if theres multiple vectors? For example my book gives
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Int main()
{
vector<string> inventory;
inventory.push_back("sword");
inventory.push_back("armour");
inventory.push_back("shield");
vector<string>::iterator myIterator;
vector<string>::const_iterator iter;
cout << "Your items:\n";
for (iter=inventory.begin(); iter != inventory.end(); ++iter)
{
cout << *iter << endl;
}
}
How does myIterator know to go through vector inventory if there are other vectors. Or is iter what goes through the vecotr and myIterator is just a holding block for new information
I see that you are not using myIterator.
iter knows which vector to iterate through (in this case inventory) as you have iter=inventory.begin(); iter != inventory.end();
@football52 - Maybe this will help clear up some confusion.
At line 9, you defined a const_iterator called iter. At the moment, iter doesn't point to anything so it's not associated with inventory yet. In fact, it can be used as an iterator for any vector<string>.
At line 12, you're making the association with inventory by assigning the address of the first element of inventory (inventory.begin()) to iter. Each time through the loop iter++ causes iter to point to the next element of the vector. The for loop continues as long as iter has not reached inventory.end()