一行断言以测试STL容器是否已排序

Gho*_*der 13 c++ arrays assert stl

有没有办法写一个单行条件,如果STL容器被排序,它将返回true?有问题的容器是std :: vector

我打算在断言中使用它

aJ.*_*aJ. 23

adjacent_find与更少或更多的仿函数结合使用.

限制:
您应该知道容器是按升序还是按降序排序.

如果vector应该按升序排序:

//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;
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*yan 8

您可以使用std :: is_sorted(vec.begin(),vec.end())来测试它是否已排序.但请注意,这是O(n).

  • `is_sorted`不是C++标准库的一部分. (6认同)
  • 它符合C++ 0x标准 - 并附带VC++ 2010 (4认同)