algorithm - STL C++

is_sorted()

Declaration

template <class FwdIterator>
bool is_sorted(
	FwdIterator xFirst,
	FwdIterator xLast
);

Description

This function tests the range of entries starting at "xFirst" up to the one before "xLast" to determine whether the set of all entries in the range are sorted. In the overloaded version, the function "xComp" is used as the ordering function.

Header Include

#include <algorithm>

Overloads

template <class FwdIterator, class BinaryPredicate>
bool is_sorted(
	FwdIterator xFirst,
	FwdIterator xLast,
	BinaryPredicate xComp
);

Example

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
	using namespace std;

	// Create a vector instance
	vector<char> qV;
	qV.push_back('X');
	qV.push_back('o');
	qV.push_back('a');
	qV.push_back('X');
	qV.push_back('.');
	qV.push_back('n');
	qV.push_back('e');
	qV.push_back('t');

	vector<char>::iterator qIter;
	// Output the vector
	cout << "The vector: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}

	// Sort test
	bool bIsSorted = is_sorted(qV.begin(), qV.end());
	cout << (bIsSorted ? " is " : " is not ") << "sorted." << endl;

	// Sort the vector
	sort(qV.begin(), qV.end());

	// Output the new vector
	cout << "The vector: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}

	// Sort test
	bIsSorted = is_sorted(qV.begin(), qV.end());
	cout << (bIsSorted ? " is " : " is not ") << "sorted." << endl;

	// Keep the window open
	cin.get();
	return 0;
}

Output

is_sorted() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.