如果 STL 容器已排序,有没有办法编写一个返回 true 的单行条件?有问题的容器是 std::vector
我打算在断言中使用它
最佳答案
使用 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;
}
关于c++ - 一行断言测试 STL 容器是否已排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2955082/