unordered_set equal_range() in C++

equal_range(): This function is available in the File: unordered_set.h

Syntax:

std::pair<std::unordered_set<int>::iterator, std::unordered_set<int>::iterator> std::unordered_set<int>::equal_range(const int &__x)

This function takes one argument as its parameter. This function finds a subsequence matching given key.

Parameters: One parameter is required for this function.

__x: The constant value to be compared.

Returns: Pair of iterators that possibly points to the subsequence matching given key.

Note: This function probably only makes sense for multisets.

File: unordered_set.h

Approach 1: When the given element is present in the set.

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    unordered_set<intst = {94546};

    int x = 4;

    auto it = st.equal_range(x);
    if (it.first != it.second)
    {
        for (; it.first != it.second; ++it.first)
            cout << *it.first << " ";
    }
    else
        cout << "Element " << x << " not present in set";

    return 0;
}

Output:

4


Approach 2: When a given element does not present in the set.

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    unordered_set<intst = {94546};

    int x = 100;

    auto it = st.equal_range(x);
    if (it.first != it.second)
    {
        for (; it.first != it.second; ++it.first)
            cout << *it.first << " ";
    }
    else
        cout << "Element " << x << " not present in set";

    return 0;
}

Output:

Element 100 not present in set

No comments:

Post a Comment