std :: is_sorted_until用于查找范围[first,last)中的第一个未排序元素。它将迭代器返回到范围中的第一个未排序元素,因此在first和返回的迭代器之间的所有元素都进行了排序。
它也可以用来计算总数。范围内已排序元素的数量。它在头文件中定义。如果整个范围都已排序,它将返回一个指向last的迭代器。
可以按以下两种方式使用它:
使用“ <”比较元素:
句法:
template
ForwardIterator is_sorted_until (ForwardIterator first, ForwardIterator last);
first: Forward iterator to the first element in the list.
last: forward iterator to the last element in the list.
Return Value: It returns an iterator to the first
unsorted element in the list.
It returns last in case if there is only one element in
the list or if all the elements are sorted.
CPP
// C++ program to demonstrate the use of std::is_sorted_until
#include
#include
using namespace std;
int main()
{
int v[] = { 1, 2, 3, 4, 7, 10, 8, 9 }, i;
int* ip;
// Using std::is_sorted_until
ip = std::is_sorted_until(v, v + 8);
cout << "There are " << (ip - v) << " sorted elements in "
<< "the list and the first unsorted element is " << *ip;
return 0;
}
CPP
// C++ program to demonstrate
// the use of std::nth_element
// C++ program to demonstrate the
// use of std::nth_element
#include
#include
using namespace std;
// Defining the BinaryFunction
bool comp(int a, int b) { return (a < b); }
int main()
{
int v[] = { 1, 3, 20, 10, 45, 33, 56, 23, 47 }, i;
int* ip;
// Using std::is_sorted_until
ip = std::is_sorted_until(v, v + 9, comp);
cout << "There are " << (ip - v)
<< " sorted elements in "
<< "the list and the first unsorted element is "
<< *ip;
return 0;
}
输出:
There are 6 sorted elements in the list and the first unsorted element is 8
通过使用预定义函数进行比较:
句法:
template
ForwardIterator is_sorted_until (ForwardIterator first, ForwardIterator last,
Compare comp);
Here, first and last are the same as previous case.
comp: Binary function that accepts two elements in the
range as arguments, and returns a value convertible to bool.
The value returned indicates whether the element passed as
first argument is considered to go before the second in the specific
strict weak ordering it defines.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
Return Value: It returns an iterator
to the first unsorted element in the list.
It returns last in case if there is only one element in
the list or if all the elements are sorted.
CPP
// C++ program to demonstrate
// the use of std::nth_element
// C++ program to demonstrate the
// use of std::nth_element
#include
#include
using namespace std;
// Defining the BinaryFunction
bool comp(int a, int b) { return (a < b); }
int main()
{
int v[] = { 1, 3, 20, 10, 45, 33, 56, 23, 47 }, i;
int* ip;
// Using std::is_sorted_until
ip = std::is_sorted_until(v, v + 9, comp);
cout << "There are " << (ip - v)
<< " sorted elements in "
<< "the list and the first unsorted element is "
<< *ip;
return 0;
}
输出:
There are 3 sorted elements in the list and the first unsorted element is 10
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。