forked from teseoch/CPP-Fall-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path55-iterators.cpp
72 lines (59 loc) · 1.48 KB
/
55-iterators.cpp
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
68
69
70
71
72
#include <iostream>
#include <string>
#include <vector>
/* print_vector( V )
Print out each element in a vector of ints, in forward order.
*/
void print_vector(const std::vector<int> &V)
{
// for (auto x : V)
// {
// std::cout << x << " ";
// }
// std::cout << std::endl;
// Task: Rewrite this using an iterator instead of a for-each loop
for (auto it{V.begin()}; it != V.end(); ++it)
{
std::cout << *it << " ";
}
std::cout << std::endl;
}
/* print_reverse( V )
Print out each element in a vector of ints, in reverse order.
*/
void print_reverse(std::vector<int> V)
{
// for (int i = 0; i < V.size(); ++i)
// {
// //bla
// }
// for (int i = V.size() - 1; i >= 0; --i)
// {
// //bla
// }
// // auto it{V.end()};
// Task: Write this without using indices
for (auto it{V.rbegin()}; it != V.rend(); ++it)
{
std::cout << *it << " ";
}
std::cout << std::endl;
}
int main()
{
std::vector<int> V{6, 8, 10, 17};
std::cout << "Before : ";
print_vector(V);
auto iter = V.begin(); //not a pointer, but an iterator
std::cout << "Part 1: iter refers to " << *iter << std::endl;
++iter;
iter++;
std::cout << "Part 2: iter refers to " << *iter << std::endl;
*iter = 42;
std::cout << "Part 3: iter refers to " << *iter << std::endl;
std::cout << "After: ";
print_vector(V);
std::cout << "In reverse: ";
print_reverse(V);
return 0;
}