Question on Iterators

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;
	}
An iterator "points to" (indirectly identifies) an element in a sequence.

The iterator itself (iter) is not the element; the result of the dereference (*iter) is the element in the sequence.
OP: since C++11 you can also use range based for loops in such cases:
1
2
3
4
for (const auto& elem : elements)
{
    std::cout << elem << "\n";
}

http://en.cppreference.com/w/cpp/language/range-for
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.

To output a container we could use std::copy.
1
2
vector<int> v = {1, 2, 3, 4, 5};
copy(v.begin(), v.end(), ostream_iterator(cout, " ");
According to Bjarne Stroustrup we should rarely need to write for loops over container

was Stroustrup referring to the traditional for loops or the range-based for loops?
Last edited on
Before C++11 there was no range-based for loop
range based loops lose the iterators, so when access to iterators become necessary there is no way around using for loops of the traditional variety
I think there will always be exceptions to rules.
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
Topic archived. No new replies allowed.