The Wayback Machine - https://web.archive.org/web/20210520085154/https://www.geeksforgeeks.org/find-index-of-an-element-in-a-set-in-c/
Skip to content
Related Articles

Related Articles

Find index of an element in a Set in C++
  • Last Updated : 18 May, 2021

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

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) 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :