algorithm - STL C++

lexicographical_compare()

Declaration

template <class InputIterator1, class InputIterator2>
bool lexicographical_compare(
	InputIterator1 xFirst1,
	InputIterator1 xLast1,
	InputIterator1 xFirst2,
	InputIterator1 xLast2
);

Description

This function does a lexicographical comparison on the items in the range from "xFirst1" up through the one before "xLast1" with the range of items from "xFirst2" up through the one before "xLast2" and returns true is the first range comes before second. Otherwise, it returns false. The overloaded version uses the function "xComp" as a comparison function.

Header Include

#include <algorithm>

Overloads

template <class InputIterator1, class InputIterator2, class BinaryPred>
bool lexicographical_compare(
	InputIterator1 xFirst1,
	InputIterator1 xLast1,
	InputIterator1 xFirst2,
	InputIterator1 xLast2,
	BinaryPred xComp
);

Example

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

int main()
{
	using namespace std;

	// Create two vector instances
	vector<char> qV1;
	qV1.push_back('X');
	qV1.push_back('o');
	qV1.push_back('a');
	qV1.push_back('X');
	qV1.push_back('.');
	qV1.push_back('n');
	qV1.push_back('e');
	qV1.push_back('t');

	vector<char> qV2;
	qV2.push_back('M');
	qV2.push_back('i');
	qV2.push_back('k');
	qV2.push_back('e');
	qV2.push_back(' ');
	qV2.push_back('H');
	qV2.push_back('a');
	qV2.push_back('l');
	qV2.push_back('l');

	vector<char>::iterator qIter;
	cout << "V1 = ";
	for (qIter = qV1.begin(); qIter != qV1.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	cout << "V2 = ";
	for (qIter = qV2.begin(); qIter != qV2.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	// Compare two vectors
	bool bComp = lexicographical_compare(
		qV1.begin(), qV1.end(), qV2.begin(), qV2.end());
	cout << "V1 " << (bComp ? "is" : "is not")
		<< " less than V2." << endl;

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

Output

lexicographical_compare() Output
 

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