10

About ostream of c ++

 2 years ago
source link: https://www.codesd.com/item/about-ostream-of-c.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

About ostream of c ++

advertisements
map<string,int> m;
string str;
while (cin >> str){
    ++m[str];
}
map<string, int>::const_iterator iter = m.begin();

while (iter != m.end()){
    cout << iter->first << (iter++)->second << endl;
}
return 0;

above is the code,but compiler give me a error about invalid dereference,so I change last line like that:

cout<<(iter++)->first<<iter->second<<endl;

and I got right answer,my question is what cout have done make me have to write like this,Is it read string from back to front?how does it implement? or am I wrong other place?


Given an expression of the form a << b, a and b must both be evaluated, but the order they are evaluated is unspecified, which means any order is permitted (a first, b first, both concurrently somehow).

The same goes when multiple such expressions are chained, such as a << b << c.

Practically, overloaded operators are implemented as function calls. For example

std::cout << iter->first << (iter++)->second;   // drop  << endl for simplicity of discussion

may be expanded to something like

operator<<(operator<<(std::cout << iter->first), (iter++)->second);

The order of evaluation of function arguments is also unspecified. So the order of evaluating operator<<(std::cout << iter->first) and (iter++)->second) before passing them to the outermost call of operator<<().

It just so happens with your compiler that (iter++)->second) is evaluated before operator<<(std::cout << iter->first), even though you were expecting the opposite.

The solution is not to mix too many operations with side effects in one statement, because that is a good way to trip over such ordering concerns. In your case, do the output, and increment iter in the next statement.

cout << iter->first << iter->second << endl;
++iter;




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK