-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathauto.cpp
More file actions
67 lines (42 loc) · 1.33 KB
/
auto.cpp
File metadata and controls
67 lines (42 loc) · 1.33 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
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main()
{
// this program demonstrates the use of keyword "auto"
// KEEP IN MIND THAT THIS WILL ONLY WORK WITH C++ 11 AND ABOVE
// auto is used for type inference.
// It automatically deduces the data type of an expression
// For example,
auto num = 10;
cout << num + 5 << endl;
// It can be used when we are dealing with complex data structures and are unsure of it's data type.
// For example, suppose you have a map
map<int,int>myMap;
for(int i=0; i<5; i++){
myMap[i] += i;
}
// Now the basic method of iterating through map is
/*
for (map<int,int>::iterator it=myMap.begin(); it!=myMap.end(); ++it){
cout << it->second << endl;
}
*/
// But with auto it can be reduced to
for(auto it : myMap){
cout << it.second << endl;
}
// More examples -
// Suppose you have an array of sets
set<int> mySet[5];
mySet[2].insert(5);
mySet[2].insert(3);
// You have to print all the elements in mySet[2]
// Now instead of writing it's complex iterator, we can just use auto
for(auto it : mySet[2]){
cout << it << endl;
}
// So, we see that, auto can be used as a substitute for complex iterators
return 0;
}