C ++ Input: Solaris vs. Workflow Linux

I have a very simple test program that uses istringstreams to read in integers from std :: string. The code:

std::map<int, int> imap; int idx, value; std::string str("1 2 3 4 5 6 7 8"); istringstream is(str); while(is >> idx >> imap[idx]){ cout << idx << " " << imap[idx] << endl; } cout << endl; std::map<int, int>::iterator itr; for(itr = imap.begin(); itr != imap.end(); itr++){ cout << itr->first << " " << itr->second << endl; } 

When I run this on Solaris 10, it produces the following output:

 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 

However, when I run it under CentOS 7, I get:

 1 0 3 0 5 0 7 0 1 4 3 6 5 8 7 0 4204240 2 

Does anyone know why this would be different on Linux than on Solaris? He obviously reads the value in the map before reading into the index for the map, but I don't know why. I can make it work under Linux by slightly modifying the code:

 std::map<int, int> imap; int idx, value; std::string str("1 2 3 4 5 6 7 8"); istringstream is(str); while(is >> idx >> value){ imap[idx] = value; cout << idx << " " << imap[idx] << endl; } std::map<int, int>::iterator itr; for(itr = imap.begin(); itr != imap.end(); itr++){ cout << itr->first << " " << itr->second << endl; } 

I know this is a valid solution, but I have people around me who want to know why this is different. We are moving from Solaris to Linux, and when such things arise, they want to know why. I do not know why, therefore, I ask for advice.

+5
source share
1 answer
 is >> idx >> imap[idx] 

This expression is equivalent

 operator>>(operator>>(is, idx), imap.operator[](idx)) 

The estimates of the arguments of the same function are independent of each other; either operator>>(is, idx) or imap.operator[](idx) can be evaluated first (that is, first you can evaluate either is >> idx or imap[idx] ). If the latter is evaluated first, then the result is an lvalue referring to the value corresponding to the old idx value on the map; this value will be overwritten by the second read, and not the value corresponding to the new idx value.

The modified code fixes this by ensuring that idx read before access to imap[idx] .

+5
source

Source: https://habr.com/ru/post/1211115/


All Articles