(M) Type inference (auto)¶
It was mentioned earlier
that the programmer can leave variable’s type to be concluded by the compiler.
For this purpose C++ has the keyword auto.
This kind of type inference is easy for the writer of the code, but
in some cases (especially with containers) it would be easier for the reader
to understand the code, if the exact type name was visible.
In this exercise, you will practice replacing auto with the exact
type name.
The code below uses bad naming (e.g. var1, var2, etc.) on purpose
to prevent deduction based on names used.
Look at the code and consider, which type could be in the place of the
word auto.
/* 1 */ #include <iostream>
/* 2 */ #include <map>
/* 3 */ #include <vector>
/* 4 */ #include <set>
/* 5 */
/* 6 */ using namespace std;
/* 7 */
/* 8 */ using MapType = map<string, map<string, vector<int>>>;
/* 9 */ using VectorType = vector<map<string, set<int>>>;
/* 10 */
/* 11 */ int main()
/* 12 */ {
/* 13 */ MapType myMap;
/* 14 */ for(auto var1 : myMap)
/* 15 */ {
/* 16 */ for(auto var2 : var1.second)
/* 17 */ {
/* 18 */ for(auto var3 : var2.second)
/* 19 */ {
/* 20 */ cout << var3 << endl;
/* 21 */ }
/* 22 */ }
/* 23 */ }
/* 24 */
/* 25 */ VectorType myVector;
/* 26 */ for(auto var1 : myVector)
/* 27 */ {
/* 28 */ for(auto var2 : var1)
/* 29 */ {
/* 30 */ for(auto var3 : var2.second)
/* 31 */ {
/* 32 */ cout << var3 << endl;
/* 33 */ }
/* 34 */ }
/* 35 */ }
/* 36 */
/* 37 */ return 0;
/* 38 */ }