views:

226

answers:

3

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  A: 

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

Michael Aaron Safyan
`is_sorted` isn't a part of the C++ Standard Library.
Kirill V. Lyadvinsky
It is in the C++0x standard - and shipping with VC++ 2010
corvuscorax
@corvuscorax, yes it is in C++0x, but it is only draft unfortunately. [I wouldn't use it in a production code.](http://stackoverflow.com/questions/1754397/how-are-you-using-c0x-today)
Kirill V. Lyadvinsky
A: 

It depends what STL data type you want to use.

A map is already sorted by the key provided the key has overloaded compare operators. You're good to go here.

A list requires that you explicitly call the sort function. You will need to keep track of whether or not you sorted it yet.

Hope this helps.

Ben Burnett
+8  A: 

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;
}
aJ
Beat me by a second.
GMan
Well known trick, though not so obvious. Fortunately C++0x introduces the `is_sorted` function for that :)
Matthieu M.