Generic method to access the nth element
In order to access the nth element from the set we can create a generic method. In this method, we will return two values which are: a boolean value if the nth element is present or not, and if present then what will be the value of that element?
Example:
C++
// C++ program to access // element by index in set. #include <bits/stdc++.h> using namespace std; template < typename T> pair<T, bool > get_nth_element(set<T>& set_name, int index) { pair<T, bool > val; if (set_name.size() > index) { auto it = next(set_name.begin(), index); val.first = *it; val.second = true ; } else val.second = false ; return val; } int main() { set< int > s; // Inserting values in set s.insert(10); s.insert(20); s.insert(30); s.insert(40); s.insert(50); // Index int n = 3; // Accessing the nth element and returning it in // a pair named final. pair< int , bool > final = get_nth_element(s, n); if (final.second == true ) cout << final.first; else cout << "nth element is not present in the set." ; return 0; } |
Output
40
How to Access Elements in Set by Index in C++?
Sets are the containers that are available in the C++ Standard Template Library (STL). They are used to hold distinct elements in a predetermined sequence; fundamentally, it operates on the same principles as a binary search tree.
In C++, elements can be added to or removed from sets, but they cannot be modified after being stored there since their values become constant. The following methods are available to access elements in a set by index in C++ STL:
- Accessing the element by iterating in the set.
- Accessing the element at a particular index using the next() function.
- Accessing the element at a particular index using the advance() function.
- By Creating Generic methods to access the nth element from any set
Contact Us