In the C 17 for loop syntax for(auto [key, val]: students), what is auto replacing?
If students was, for example std::map<int,char*>, what would be written if not auto? I don't understand what it even is taking the place of. [int,char*]?
CodePudding user response:
type [a,b,c] is a structured binding, and those force you to use auto (possibly decorated with const and/or &/&&).
But aside from that, auto expands to the same type it would expand to if [...] was replaced with a variable name. In
for (auto elem : students)
... auto expands to std::pair<const int, char *>.
In a structured binding it expands to the same type, but the resulting "variable" of this type is unnamed.
Then, for each name in brackets, a reference (or something similar to a reference) is introduced, that points to one of the elements of that unnamed variable.
CodePudding user response:
The std::map is filled with std::pair<int, char*>, so one way to write this loop would be
for (std::pair<int, char*> pair : students)
We could also separate the pair with std::tie, but this syntax cannot be used in the loop:
int key;
char* value;
std::pair<int, char*> pair;
std::tie(key, value) = pair;
Statement auto [key, val] replaces std::tie. This syntax is called structured binding.
