有没有办法写一个单行条件,如果对STL容器进行排序,它将返回true?有问题的容器是std :: vector
我打算在断言中使用它
答案 0 :(得分: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;
}
答案 1 :(得分:8)
您可以使用std::is_sorted(vec.begin(),vec.end())来测试它是否已排序。但请注意,这是O(n)。
答案 2 :(得分:0)
这取决于您要使用的STL数据类型。
如果密钥重载了比较运算符,则映射已按密钥排序。你很高兴来到这里。
列表要求您显式调用sort函数。您需要跟踪是否对其进行了排序。
希望这有帮助。