c++ - 一行断言测试 STL 容器是否已排序

标签 c++ arrays stl assert

如果 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/

相关文章:

c++ - GoogleTest for Android NDK C++ with CMake

php - foreach 只查找数组的最后一个元素

来自索引数组的python numpy数组

c++ - 为什么 STL_tree.h 中的 end() 返回对迭代器对象的引用,而 begin() 返回对象?

c++ - 为什么 numeric_limits<int>::min() 有不同的定义?

c++ - 最快的排序功能

c++ - 用更大的数组覆盖数组

c++ - 链接 : fatal error LNK1104: cannot open file 'libcollada14dom21.lib'

php - 在 PHP 中使用 array_chunk 移动元素

c++ - 在 3 个字符串 vector 中查找连接