What is wrong here? associativity? assessment procedure? How to change the order?

The associativity of the rtl stream insertion operator, forgetting that this fact sometimes leads to runtime errors or logical errors. eg:

the first -

int F()
{
   static int internal_counter c=0;
   return ++c;
}

in the main function:

//....here is main()
cout<<"1st="<<F()<<",2nd="<<F()<<",3rd="<<F();

and output:

1st=3,2nd=2,3rd=1

which is different from what we expect at the beginning.

2nd- suppose we have an implementation of a stack data structure like this:

    //
    //... a Stack<DataType> class …… 
    //

    Stack<int> st(10);
    for(int i=1;i<11;i++)
       st.push(i);

cout<<st.pop()<<endl<<st.pop()<<endl<<st.pop()<<endl<<st.pop()<<endl;

the expected result looks something like this:

10
9
8
7

but we have:

7
8
9
10

There is no internal error <<but it can be so confusing ... and finally [:-)] my question is: is there a way to change the associativity of the operator by overloading it?

Do you think this could be the other way around? I mean, is it possible to reorder by changing or changing the open source STL?

+3
source share
3

, -, . . Β§5.4 - 5.18 . << , . , ++, ( ) " " && & || .

+5

, . , . , , & &, || , (). :

cout<<st.pop()<<endl<<st.pop()<<endl<<st.pop()<<endl<<st.pop()<<endl;

, st.pop() , , .

+10

To find out how this is an evaluation problem, not an associativity problem, change your code to this:

int a = st.pop();
int b = st.pop();
int c = st.pop();
cout << a << endl << b << endl << c << endl;
+2
source

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


All Articles