To answer the question of a problem, it is necessary to determine whether the sequence is sorted in ascending order or there are violations of order in it. I do not know C ++ well and it would be clearer to write the list myself, but it would be more convenient to take a ready-made abstraction. What am I doing wrong when using iterators? In the last step, the iterator points to the very top of the list, and because of this, the result is incorrect.

#include <iostream> #include <list> #include <ctype.h> int main(){ std::list<int> balls; int n, ball, curr; bool cheater; std::cin >> n; while(!std::cin.eof()){ std::cin >> ball; balls.push_back(ball); } cheater = false; std::list<int>::iterator it = balls.begin(); while(it != balls.end()){ std::cout << *it << " "; curr = *it; if(curr >= *(++it)) cheater = true; std::cout << "curr = " << curr << ", it = " << *it << std::endl; curr = *it; //it++; } 

https://ideone.com/GhVr70

    1 answer 1

    In order to determine whether a sequence is sorted, it suffices to use the standard algorithm std::is_sorted , defined in the header of the <algorithm> .

    For example,

     #include <algorithm> //... bool cheater = std::is_sorted( balls.begin(), balls.end() ); 

    As for your code, this offer

      if(curr >= *(++it)) cheater = true; 

    has undefined behavior when it points to the last element.

    Keep in mind that this cycle

     while(!std::cin.eof()){ std::cin >> ball; balls.push_back(ball); } 

    is incorrect.

    It will be correct to write

     while(std::cin >> ball){ balls.push_back(ball); } 

    Otherwise, you can write to the list the item that you did not enter.

    • "It will be correct to write down" It is strange, and in some task I tried to make a cycle in a style when the result of an assignment expression is used as a condition, but that code was not compiled. Also used std :: cin in the condition. When the items have run out, does cin return 0? - typemoon
    • @typemoon When the elements run out, it uses the transform operator to bool, and returns false. - Vlad from Moscow
    • And why this program gives the wrong result? After all, the list is ordered. The answer became incorrect after I changed the list filling cycle. ideone.com/HEvzDr - typemoon
    • @typemoon The program works correctly. Your list is not sorted in ascending order. - Vlad from Moscow