-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrangeForLoops.cpp
More file actions
67 lines (45 loc) · 1.42 KB
/
rangeForLoops.cpp
File metadata and controls
67 lines (45 loc) · 1.42 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
C++11 onwards the C++ also supports Range based for Loops
This adds more generic nature to the looped blocks
Used as a more readable equivalent to the traditional for loop
operating over a range of values, such as all elements in a container.
The program below also demos the use of keyword auto for variables.
*/
#include <iostream>
#include <vector>
using namespace std;
int main() {
int numbers[] = { 11, 22, 33, 44, 55 };
// For each member called number of array numbers - read only
for (int number : numbers) {
cout << number << endl;
}
// To modify members, need to use reference (&)
for (int &number : numbers) {
number = 99;
}
for (int number : numbers) {
cout << number << endl;
}
/* USE OF AUTO in RANGE BASED FOR LOOPS */
cout << "\n AUTO KEYWORD DEMO \n";
std::vector<int> v = { 0, 1, 2, 3, 4, 5 };
for (const int &i : v) // access by const reference
std::cout << i << ' ';
std::cout << '\n';
for (auto i : v) // access by value, the type of i is int
std::cout << i << ' ';
std::cout << '\n';
for (auto&& i : v) // access by reference, the type of i is int&
std::cout << i << ' ';
std::cout << '\n';
for (int n : {0, 1, 2, 3, 4, 5}) // the initializer may be a braced-init-list
std::cout << n << ' ';
std::cout << '\n';
int a[] = { 0, 1, 2, 3, 4, 5 };
for (int n : a) // the initializer may be an array
std::cout << n << ' ';
std::cout << '\n';
system("pause");
return 0;
}