one line assert to test if STL container is sorted

后端 未结 3 1565
自闭症患者
自闭症患者 2021-02-05 16:22

Is there a way to write a one line condition that would return true if STL container is sorted? The container in question is std::vector

I intend to use it in an assert<

3条回答
  •  梦如初夏
    2021-02-05 16:56

    Use adjacent_find in combination with less or greater functor.

    Restriction:
    You should know whether the container is sorted in ascending or descending.

    If the vector is supposed to be sorted in ascending order:

    //Checks the first element where adjacent value where elem > nextElem
    //returns end if the vector is sorted!
    //Complexity is O(n)
    vector::iterator pos =  std::adjacent_find (aVec.begin(), aVec.end(),   // range
                                         std::greater());               
    
    
    if (pos == aVec.end()) 
    {
        std::cout<<" sorted"<

提交回复
热议问题