Open In App

Find index of an element in a Set in C++

Improve
Improve
Like Article
Like
Save
Share
Report

Given a set S consisting of N integers and an element K, the task is to find the index of the element K in the set S. If the element is not present in S, print -1.

Examples:

Input: N = 5, S = {1, 2, 3, 4, 6} K = 6
Output: 5
Explanation: 6 is the 5th element in S.

Input: N = 5, S = {1, 2, 3, 4, 6}, K = 5
Output:  -1  
Explanation:  5 is not present in this set so we give output as -1.

Approach: Follow the steps below to solve the problem:

  • Initialize a variable, say index as 1, to store the index of the required element.
  • Traverse the set S and perform the following operations: 
  • If the current element is K, print Index and break out of the loop.
  • Otherwise, increment Index.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate index
// of element in a Set
int GetIndex(set<int> S, int K)
{
 
    // To store the index of K
    int Index = 1;
 
    // Traverse the Set
    for (auto u : S) {
 
        if (u == K)
            return Index;
 
        Index++;
    }
 
    // If K is not present
    // in the set
    return -1;
}
 
// Driver Code
int main()
{
    // Input
    set<int> S;
    S.insert(1);
    S.insert(6);
    S.insert(2);
    S.insert(3);
    S.insert(4);
    int K = 6;
 
    cout << GetIndex(S, K) << endl;
    return 0;
}


Output: 

5

 

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



Last Updated : 01 Jul, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads