I understand that the asterisk is a dereferencing operator, however is it required to use when trying to output what is within a vector onto the screen? The top portion of the code works, but the bottom half gives me an error. No code is needed, just some extra info to wrap my head around the basics.
1 2 3 4 5 6 7 8 9 10 11 12 13
//This works
cout << "Show elements:\n";
for (iter = elements.begin(); iter != elements.end(); ++iter)
{
cout << *iter << endl;
}
//This doesn't work
cout << "\nShow elements:\n";
for (iter = elements.begin(); iter != elements.end(); ++iter)
{
cout << iter << endl;
}
According to Bjarne Stroustrup we should rarely need to write for loops over container. His advice is to use the stl algorithms instead. His advice was before C++11, so I am not sure if it is still useful.
Note that a range-for loop is a deliberately simple construct. For example, using it you can’t touch two elements at the same time and can’t effectively traverse two ranges simultaneously. For that we need a general for-statement
- Stroustrup