Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one line assert to test if STL container is sorted

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

like image 655
Ghostrider Avatar asked Jun 02 '10 04:06

Ghostrider


2 Answers

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<int>::iterator pos =  std::adjacent_find (aVec.begin(), aVec.end(),   // range
                                     std::greater<int>());               


if (pos == aVec.end()) 
{
    std::cout<<" sorted"<<endl;
}
else
{
    std::cout<<"Not sorted"<<endl;
}
like image 168
aJ. Avatar answered Nov 10 '22 01:11

aJ.


You can use std::is_sorted(vec.begin(),vec.end()) to test if it is sorted. Note, though, that this is O(n).

like image 28
Michael Aaron Safyan Avatar answered Nov 10 '22 01:11

Michael Aaron Safyan