- C++ Programs, cpp-set, Searching, STL

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

Find index of an element in a Set in C++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 = 6Output: 5Explanation: 6 is the 5th element in S.Input: N = 5, S = {1, 2, 3, 4, 6}, K = 5Output: 1Approach: 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++  #include using namespace std;  int GetIndex(set S, int K){          int Index = 1;          for (auto u : S) {          if (u == K)            return Index;          Index++;    }              return -1;}  int main(){        set S;    S.insert(1);    S.insert(6);    S.insert(2);    S.insert(3);    S.insert(4);    int K = 6;      cout