(K) Type inference (auto)¶
On previous round (section 4.1), it was told 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 practise replacing auto
with the exact
type name.
Let’s look at the code below, where types and variables have been named
badly on purpose:
/* 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 */ }