First commit
[cpp_sandbox.git] / Sandbox / IfAndSwitchInitStatements.cpp
1 #include "IfAndSwitchInitStatements.h"
2
3 #include <iostream>
4 #include <vector>
5 #include <algorithm>
6 using namespace std;
7
8 // Ep 21: https://www.youtube.com/watch?v=AiXU5EuLZgc
9
10 namespace IfAndSwitchInitStatements
11 {
12 vector<int> make_vec()
13 {
14 return { 1, 2, 3, 4 };
15 }
16 }
17
18 void IfAndSwitchInitStatements::tests()
19 {
20 auto vec = make_vec();
21
22 // Same for 'switch' block.
23 if (const auto itr = find(vec.begin(), vec.end(), 2);
24 itr != vec.end())
25 {
26 *itr = 42;
27 }
28 else
29 {
30 vec.push_back(42);
31 }
32
33 // Declare an variable into a if condition allows to use this variable only in the if scope
34 // and will not get out of scope.
35 // Here we can reuse the name 'itr' previously used in the previous if statement.
36 if (const auto itr = find(vec.begin(), vec.end(), 3);
37 itr != vec.end())
38 {
39 *itr = 43;
40 }
41 else
42 {
43 vec.push_back(43);
44 }
45
46 for (auto i = vec.begin(); i != vec.end(); ++i)
47 {
48 if (i != vec.begin())
49 cout << ", ";
50 cout << *i;
51 }
52
53 cout << endl;
54 }