Range-based for on std::vector

Hi,

Can't we define auto so that it provides us with an iterator to the elements of the STL container as in the code below?

1
2
3
4
5
6
7
int main() {
    std::vector<int> v = {0, 1, 2, 3, 4, 5};
 
    for (auto i : v) // access by an iterator 
        std::cout << *i << ' ';  // print the values 
    std::cout << '\n';
}


I looked the web up much but couldn't find that style. I know we can access the data by value but I liked to know if it's possible to use an iterator and then dereference it in std::cout.
Last edited on
i is not an iterator - but a copy of the element of the vector. You don't de-reference this, just use it.

To access the elements using an iterator:

1
2
3
4
5
6
7
8
9
10
11
12
#include <vector>
#include <iostream>

int main() {
	const std::vector<int> v {0, 1, 2, 3, 4, 5};

	for (auto it = v.cbegin(); it != v.cend(); ++it)
		std::cout << *it << ' ';  // print the values

	std::cout << '\n';
}


To use a range-for:

1
2
3
4
5
6
7
8
9
10
11
#include <vector>
#include <iostream>

int main() {
	const std::vector<int> v {0, 1, 2, 3, 4, 5};

	for (const auto& i : v)
		std::cout << i << ' ';  // print the values

	std::cout << '\n';
}

Thank you for your answer.
Topic archived. No new replies allowed.