Related Articles

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

• Last Updated : 01 Jul, 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
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 ``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)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up