Question on Iterators

May 19, 2017 at 3:47am
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;
	}
May 19, 2017 at 4:04am
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.
May 19, 2017 at 10:47am
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
May 19, 2017 at 12:27pm
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, " ");
May 19, 2017 at 12:34pm
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 May 19, 2017 at 12:34pm
May 19, 2017 at 12:50pm
Before C++11 there was no range-based for loop
May 19, 2017 at 1:29pm
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
May 19, 2017 at 2:13pm
I think there will always be exceptions to rules.
May 19, 2017 at 3:16pm
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.