C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ set begin()C++ set begin() function is used to return an iterator referring to the first element of the set container. Syntaxiterator begin(); //until C++ 11 const_iterator begin() const; //until C++ 11 iterator begin() noexcept; //since C++ 11 const_iterator begin() const noexcept; //since C++ 11 ParameterNone Return valueIt returns an iterator pointing to the first element of the set. ComplexityConstant. Iterator validityNo changes. Data RacesThe container is accessed. Neither the constant nor the non-constant versions modify the container. Exception SafetyThis function never throws exceptions. Example 1Let's see the simple example for begin() function: #include <iostream> #include <set> using namespace std; int main () { set<string> myset= {"Java", "C++", "SQL"}; // show content: cout<<"Contents of myset are: "<<endl; for (set<string>::iterator it=myset.begin(); it!=myset.end(); ++it) cout << *it<< '\n'; return 0; } Output: Contents of myset are: C++ Java SQL In the above example, begin() function is used to return an iterator pointing to the first element in the myset set. Example 2Let's see a simple example: #include <iostream> #include <set> using namespace std; int main() { set<int> c; c.insert(5); c.insert(2); c.insert(4); c.insert(1); c.insert(0); c.insert(9); set<int>::iterator i = c.begin(); while (i != c.end()) cout << *i++ << " "; cout << endl; } Output: 0 1 2 4 5 9 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 = { "Nikita","Deep","Priya","Suman","Aman" }; cout<<"Elements of myset are: "<<endl; set<string>::const_iterator it; // declare an iterator it = myset.begin(); // assign it to the start of the set while (it != myset.end()) // while it hasn't reach the end { cout << *it << "\n"; // print the value of the element it points to ++it; // and iterate to the next element } cout << endl; } Output: Elements of myset are: Aman Deep Nikita Priya Suman In the above, begin() function is used to return an iterator pointing to the first element in the myset set. Example 4Let's see a simple example: #include <set> #include <iostream> int main( ) { using namespace std; set <int> s1; set <int>::iterator s1_Iter; s1.insert( 1 ); s1.insert( 2 ); s1.insert( 3 ); s1_Iter = s1.begin( ); cout << "The first element of s1 is " << *s1_Iter << endl; s1_Iter = s1.begin( ); s1.erase( s1_Iter ); s1_Iter = s1.begin( ); cout << "The first element of s1 is now " << *s1_Iter << endl; } Output: The first element of s1 is 1 The first element of s1 is now 2 In the above example, begin() function is used to return an iterator pointing to the first element in the myset set.
Next TopicSet cbegin() Function
|