The C++ vector::operator<() function is used to check whether the first vector is less than other or not, it returns true if the vector on the left side of the operator is lesser than the vector that is on the right side of the operator or else it returns false. Operator <() function compares element sequentially and comparison stops at first mismatch. This member function never throw an exception and the time complexity of the operator<() function is linear.
SyntaxFollowing is the syntax for C++ vector::operator<() Function −
bool operator<(const vector<Type, Allocator>& left, const vector<Type, Allocator>& right);Parameters
Let's consider the following example, where we are going to use the opertor<() function.
#include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v1 = {1, 2}; vector<int> v2 = {1, 2, 3, 4, 5}; if (v1 < v2) cout << "v1 is less than v2" << endl; v1.resize(5,10); if (!(v1 < v2)) cout << "v1 is greater than v2" << endl; return 0; }Output
When we compile and run the above program, this will produce the following result −
v1 is less than v2 v1 is greater than v2Example 2
Considering the another scenario, where we are going to take non equal containers and making them to compare.
#include <iostream> #include <vector> using namespace std; int main(void) { vector<int> myvector1 = {11,22,33,44,55}; vector<int> myvector2 = {11,22,33}; if (myvector1 < myvector2) cout << "myvector1 is less than myvector2" << endl; else cout << "myvector1 is not less than myvector2" << endl; return 0; }Output
On running the above program, it will produce the following result −
myvector1 is not less than myvector2Example 3
In the following example, we are going to push_back() function to insert the values and applied operator<() function.
#include <vector> #include <iostream> int main( ){ using namespace std; vector <int> myvector1, myvector2; myvector1.push_back( 1 ); myvector1.push_back( 2 ); myvector1.push_back( 4 ); myvector2.push_back( 1 ); myvector2.push_back( 2 ); myvector2.push_back( 5 ); if ( myvector1 < myvector2 ) cout << "myvector1 is less than myvector2." << endl; else cout << "myvector1 is not less than myvector2." << endl; }Output
When we execute the above program, it will produce the following result −
myvector1 is less than myvector2.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4