C++ Queue::operator<=() Function



The C++ std::queue::operator<=() function is used to compare two queue objects, determining if the left operand is less than or equal to the right one. It compares elements based on the First-In-First-Out (FIFO) manner. It return a boolean value true if the left queue is less than or equal to the right one, 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 or equal to second otherwise false.

Example

Let's look at the following example, where we are going to compare the sizes of the queue.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a, b;
    for (int x = 0; x < 3; ++x)
        a.push(x);
    for (int x = 0; x < 5; ++x)
        b.push(x);
    if (a.size() <= b.size())
        std::cout << "Queue1 is smaller or equal to Queue2.";
    else
        std::cout << "Queue1 is larger than Queue2.";
    return 0;
}

Output

Output of the above code is as follows −

Queue1 is smaller or equal to Queue2.

Example

In the following example, we are going to compare the front element of the both the queues.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a, b;
    a.push(11);
    a.push(2);
    b.push(1);
    b.push(3);
    if (a.front() <= b.front())
        std::cout << "Front element of queue1 is smaller or equal to front element of queue2. ";
    else
        std::cout << "Front element of queue1 is greater than front element of queue2.";
    return 0;
}

Output

Following is the output of the above code −

Front element of queue1 is greater than front element of queue2.

Example

Consider the following example, where we are going to compare the front element of the queue with a constant value.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    a.push(1);
    a.push(22);
    int x = 5;
    if (a.front() <= x) {
        std::cout << "Front element is less than or equal to " << x << std::endl;
    } else {
        std::cout << "Front element is greater than " << x << std::endl;
    }
    return 0;
}

Output

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

Front element is less than or equal to 5
queue.htm
Advertisements