C++ Queue::operator<() Function



The C++ std::queue::operator< function in queue is used to compare the elements lexicographically. It checks whether the first queue is less than the second queue or not and return a boolean value true if the first queue is less than second queue otherwise false. The time complexity of this function is linear i.e.O(n).

Syntax

Following is the syntax for std::queue::operator<() function.

bool operator< (const queue<T,Container>& q1, const queue<T,Container>& q2);

Parameters

  • q1 − It indicates the first queue object.
  • q2 − It indicates the second queue object.

Return value

This function returns true if first queue is less than second otherwise false.

Example

Let's look at the following example, where we are going to perform basic comparison between two queues.

#include <iostream>
#include <queue>
int main() {
    std::queue<int> a;
    std::queue<int> b;
    a.push(1);
    a.push(2);
    b.push(1);
    b.push(22);
    if (a < b) {
        std::cout << "Queue1 is less than Queue2" << std::endl;
    } else {
        std::cout << "Queue1 is not less than Queue2" << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

Queue1 is less than Queue2

Example

Consider the another scenario, where we are going to consider the queues of different size and applying operator< function.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> x;
    std::queue<int> y;
    x.push(1);
    x.push(2);
    y.push(1);
    y.push(2);
    y.push(3);
    if (x < y) {
        std::cout << "Queue1 is less than Queue2" << std::endl;
    } else {
        std::cout << "Queue1 is not less than Queue2" << std::endl;
    }
    return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

Queue1 is less than Queue2

Example

In the following example, we are going to initialize the equal queues and applying the operator< function.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    std::queue<int> b;
    a.push(1);
    a.push(2);
    b.push(1);
    b.push(2);
    if (a < b) {
        std::cout << "Queue1 is less than Queue2" << std::endl;
    } else {
        std::cout << "Queue1 is not less than Queue2" << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

Queue1 is not less than Queue2

Example

Following is the example, where we are going to compare the empty queue with non empty queue and observing the output.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    std::queue<int> b;
    b.push(123);
    if (a < b) {
        std::cout << "Queue1 is less than Queue2" << std::endl;
    } else {
        std::cout << "Queue1 is not less than Queue2" << std::endl;
    }
    return 0;
}

Output

If we run the above code it will generate the following output −

Queue1 is less than Queue2
queue.htm
Advertisements