Reputation: 20780
I have the following code snippet:
std::stringstream stream("ABC 123 CBA 321");
std::unordered_map<std::string, int> map;
std::string key;
And I'm trying to read the data like this:
stream>>key>>map[key];
Which can be rewritten as:
operator>>(stream, key).operator>>(map[key]);
Considering both >>
and .
operators have left to right associativity, can you please explain why map[key]
evaluates before key
is read from the stream?
Printing the map:
for(auto& it : map)
{
std::cout<<it.first<<" "<<it.second<<std::endl;
}
Results in:
123
ABC 321
Yes, there is a space before 123
Upvotes: 0
Views: 369
Reputation: 103703
Associativity is irrelevant here. Associativity determines which operands are bound to which operators. It does not determine in which order operand sub-expressions are evaluated. So when you say:
a >> b >> c;
Associativity dictates that the operands are grouped as (a >> b) >> c
, but it does not dictate the order in which the expressions a, b and c are evaluated. Before C++17, that order was left unspecified by the standard: this means a, b and c could be evaluated in any order. Since C++17, the order is defined to be a, then b, then c.
In other words, a compiler conforming to C++17 would print:
CBA 321
ABC 123
Or the other way around, since the container is std::unordered_map
, but not jumbled words like the output you show.
Upvotes: 2