-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathrange-iteration.cpp
More file actions
36 lines (32 loc) · 1.09 KB
/
range-iteration.cpp
File metadata and controls
36 lines (32 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Range iteration
// C++11
#include <vector>
int main()
{
int arr[] = {1, 2, 3, 4, 5};
for (int value : arr) {
// Use value
}
std::vector<int> vec = {1, 2, 3, 4, 5};
for (int& ref : vec) {
// Modify ref
}
}
// Iterate over a range of elements without using iterators or
// indices.
//
// The [range-based `for` loop](cpp/language/range-for) provides a
// simple syntax for iterating over elements of a range without using
// iterators or indices. It supports arrays, types that provide
// `begin` and `end` member functions, and types for which `begin`
// and `end` functions are found via [argument-dependent
// lookup](http://en.wikipedia.org/wiki/Argument-dependent_name_lookup).
//
// [!9-11] demonstrate iterating over an array, `arr`. In each iteration,
// `value` will have the value of each successive element of `arr`.
//
// [!14-16] similarly demonstrate iterating over a
// [`std::vector`](cpp/container/vector), `vec` (any standard
// container will also work). In this case, we have defined `ref` as a
// reference type, which will allow us to modify the objects stored
// in `vec`.