C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ set cend()C++ set cend() function is used to return a constant iterator which is next to the last entry in the set. Note:- This is a placeholder. No element exists in this location and attempting to access is undefined behavior.Syntaxconst_iterator cend() const noexcept; //since C++ 11 A const_iterator is an iterator that points to constant content. ParameterNone Return valueIt returns a constant iterator which is pointing next to the last element of the set. ComplexityConstant. Iterator validityNo changes. Data RacesThe container is accessed. Concurrently accessing the elements of a set is safe. Exception SafetyThis member function never throws exceptions. Example 1Let's see the simple example for cend() function: #include <iostream> #include <set> int main () { std::set<int> myset = {60,20,40,50,10,30}; std::cout << "myset contains:"; for (auto it=myset.cbegin(); it != myset.cend(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0; } Output: myset contains: 10 20 30 40 50 60 In the above example, cend() function is used to return an iterator pointing next to the last element in the myset set. Example 2Let's see a simple example to find the element in the set: #include <iostream> #include <string> #include <set> using namespace std; int main () { int val; set<int> c = {10,20,30,40,50}; cout<<"Enter value to find: "; cin>>val; auto result = c.find(val); //find until end of the set elements if (result != c.cend()) { cout << "Element found: "<< *result; cout << endl; } else { cout << "Element not found." << endl; } return 0; } Output: Enter value to find: 10 Element found: 10 Example 3Let's see a simple example to iterate over the set using while loop: #include <iostream> #include <set> #include <string> int main() { using namespace std; set<string> myset = {"Orange", "Banana", "Apple"}; set<string>::const_iterator it; // declare an iterator it = myset.cbegin(); // assign it to the start of the set while (it != myset.cend()) // while it hasn't reach the end { cout << *it <<endl; // print the value of the element it points to ++it; // and iterate to the next element } cout << endl; } Output: Apple Banana Orange In the above example, cend() function is used to return an iterator pointing next to the last element in the myset set. Example 4Let's see a simple example: #include <iostream> #include <set> #include <algorithm> using namespace std; int main() { set<int> c = {3, 1, 2}; for_each(c.cbegin(), c.cend(), [](const int& x) { cout << x << endl; }); return 0; } Output: 1 2 3 In the above example, cend() function is used to return an iterator pointing next to the last element in the myset set.
Next TopicSet rbegin() Function
|