Open In App

Print the element at a given index in a Set in C++

Given a Set of integers set and an integer index, the task is to find the element in the set which is present at index. If the index is beyond limits, then print “Invalid index”.
Examples: 
 

Input: sett = {11, 44, 66, 72, 88, 99}, index = 2 
Output: The element at index 2 is : 66 
Explanation: 
The element 66 is present in the set and it is present at index 2.
Input: sett = {11, 44, 66, 72, 88, 99}, index = 6 
Output: Invalid index 
 



 

Approach: 



next() function returns an iterator pointing to the element after being advanced by certain number of positions. It is defined inside the header file.

Below is the implementation of the above approach:  




// C++ program to access a
// set element by its index
 
#include <bits/stdc++.h>
using namespace std;
 
// Generic template
template <typename T>
pair<T, bool> getNthElement(set<T>& searchSet,
                            int index)
{
    pair<T, bool> result;
 
    // Check if index is valid or not
    if (searchSet.size() > index) {
        result.first
            = *(std::next(
                searchSet.begin(),
                index));
        result.second = true;
    }
 
    else
        result.second = false;
 
    // Return the pair
    return result;
}
 
// Driver Program
int main()
{
    set<int> sett = { 11, 44, 66,
                      72, 88, 99 };
    int index = 2;
 
    pair<int, bool> result
        = getNthElement(
            sett, index);
 
    if (result.second)
        cout << "The element at index "
             << index << " is "
             << result.first;
    else
        cout << "Invalid index";
    return 0;
}

Output: 
The element at index 2 is 66

 

Time Complexity: O(N) 
Auxiliary Space: O(1)
 


Article Tags :