EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

C++ begin()

By Savi JaggaSavi Jagga

Home » Software Development » Software Development Tutorials » C ++ Programming Tutorial » C++ begin()

C++ begin()

Introduction to C++ begin()

This C++ begin() is used to get the iterator pointing to the initial element of the map container. This pointer is bidirectional since it can be moved to either directions in the sequence. This function is present in map associative container class template in std namespace where elements are stored in the form of key-value pairs. Here keys are used to uniquely identify the elements values and also the elements are stored in sorted order where keys are the sorting criteria. Function requires no arguments thus is called directly using map container reference and provides guarantee of no exception when correct syntax is followed.

Syntax

Map are associative containers that store the elements in key-value pair fashion, such that no 2 elements can have 2 same keys. This contains begin() function that gives an bidirectional iterator pointing to the first element of the container.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

iterator begin() noexcept;
const_iterator begin() const noexcept;

Parameters- No parameter is required for calling begin function just map reference object is used to directly call this function using dot(.) operator.

Explanation: Here iterator  and const_iterator are two different types of iterartor which is returned according to the reference of map object calling the function.

Iterator – In case map object is not cons-qualified then member -types iterator is returned. This is a bidirectional iterator that points to the first element of the map container, and here element refers to the key-value pair.

Const_iterator – In case map reference is const-qualified then a bidirectional const-iterator is returned pointing to the first element of the cont map container and here key-value pair is referred as element.

Popular Course in this category
C++ Training (4 Courses, 5 Projects, 4 Quizzes)4 Online Courses | 5 Hands-on Projects | 37+ Hours | Verifiable Certificate of Completion | Lifetime Access | 4 Quizzes with Solutions
4.5 (5,223 ratings)
Course Price

View Course

Related Courses
Java Training (40 Courses, 29 Projects, 4 Quizzes)C Programming Training (3 Courses, 5 Project)

This function of map container guarantees to throw no exception.

How begin() function works in C++?

Map is an associative container that store the elements in key-value pair in sorted manner where elements are sorted by the key values. Here begin function helps to get an iterator pointing to the first element of the container and helps to travers through all the elements stored in the container.

When a map say :- map<datatype1, datatype1> mapObject; is declared where datatype1 and datatype2 are datatype of key and values of map reference mapObject. If one needs to traverse the elements in the given map, one needs an iterator. Thus when one calls begin function- mapObject.begin()

it is checked if map reference is const-qualified or not and depending on that corresponding function is called and returns the const_iterator or  iterator respectively. For calling begin function no parameter is required. The returned iterator is also of map function type in  key-value pair form. The returned iterator is a bidirectional iterator that means one can traverse the elements in forward as well as backward direction that helps to traverse elements in reverse order easily. This function is present in std template of map in Standard Template Library. It guarantees that no exception will be thrown while calling it, even if there is no element in the map. One must note that the returned iterator object must not be dereferenced.

Examples to Implement begin() in C++

Below are the examples mentioned:

Example #1

Let us see example of map to store percentages of students in a class against their roll numbers. In order to print there values we need an iterator to travers over all the elements in the map. This iterator is retrieved using class10.begin() function and stored in reference variable itr and traversed until end of map is reached and iterator points to an element being pointed by map.end() function. Elements from itr is accessed using itr->first and itr->Second statements.

Code:

#include <iostream>
#include <iterator>
#include <map>
using namespace std;
int main()
{
map<int, int> class10; //map declaration of key-value pair of int-int type
class10.insert(pair<int, int>(1, 65));
class10.insert(pair<int, int>(2, 78));
class10.insert(pair<int, int>(3, 60));
class10.insert(pair<int, int>(4, 50));
class10.insert(pair<int, int>(5, 90));
class10.insert(pair<int, int>(6, 80));
class10.insert(pair<int, int>(7, 75));
map<int, int>::iterator itr;  // iterator of int-int  type
cout << "\nThe map of percentages of students of  class10 is : \n";
cout << "\tRoll_no  \t Percentage\n";
for (itr = class10.begin(); itr != class10.end(); ++itr) {
cout << '\t' << itr->first
<< '\t' << itr->second << '\n';
}
cout << endl;
return 0;
}

Output:

C++ begin()1

Example #2

In this example we will try to access an iterator over an empty map and see no error or exception is thrown, but nothing is printed.

Code:

#include <iterator>
#include <map>
using namespace std;
int main()
{
map<int, int> class10;
map<int, int>::iterator itr;
cout << "\nThe map of percentages of students of  class10 is : \n";
cout << "\tRoll_no  \t Percentage\n";
for (itr = class10.begin(); itr != class10.end(); ++itr) {
cout << '\t' << itr->first
<< '\t' << itr->second << '\n';
} return 0;
}

Output:

C++ begin()2

Example #3

Lets see one example if we insert elements in unsorted order. We will see map will sort the elements according to the key values i.e roll_no since map stores the elements in sorted order only, and then values are traversed and will be printed.

Code:

#include <iostream>
#include <map>
#include <string>
int main()
{
using namespace std;
map<int,string> Student = {
{ 4, "Raj"},
{ 1, "Prakash"  },
{ 3, "Priya" },
{ 2, "Savi" },
{ 5, "Rituraj"  }};
cout<<"Students in class are:" <<endl;
map<int, string>::const_iterator myIterator;
myIterator = Student.begin();  //iterator to first element is returned
cout << "ROLL_NO"<<"\t" <<"NAME" << "\n";
while (myIterator != Student.end() )
{
cout << myIterator->first <<"\t"  << myIterator->second << "\n";
++myIterator;
}
cout << endl;
return 0;
}

Output:

rollno

Conclusion

begin() function is used to retrieve a bidirectional iterator pointing to the first element of the map , an associative container which is of same type as of the map. This function guarantees not to throw any exception and the returned iterator object must not be dereferenced if the map is empty.

Recommended Articles

This is a guide to C++ begin(). Here we discuss an introduction to C++ begin() with appropriate syntax, how does it work, and respective examples. You can also go through our other related articles to learn more –

  1. Iterator in C++
  2. C++ any()
  3. C++ test()
  4. C++ setprecision

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C plus plus Programming Tutorial
  • Functions
    • C++ getline()
    • C++ String Functions
    • Math Functions in C++
    • Friend Function in C++
    • Recursive Function in C++
    • Virtual Functions in C++
    • strcat() in C++
    • swap() in C++
    • strcmp() in C++
    • ceil function in C++
    • C++ begin()
    • size() in C++
    • C++ test()
    • C++ any()
    • C++ Bitset
    • C++ find()
    • C++?Aggregation
    • C++?String append
    • C++ String Copy
    • C++ end()
    • C++ endl
    • C++ push_back
    • C++ shuffle()
    • malloc() in C++
    • C++ reserve()
    • C++ unique()
    • C++ sort()
    • C++ find_if()
    • Reflection in C++
    • C++ replace()
    • C++ search()
    • C++ Memset
    • C++ size_t
    • C++ Substring
    • C++ Max
    • C++ absolute value
    • C++ memcpy
    • C++ wchar_t
    • C++ free()
    • C++ pair
    • C++ this
    • C++ sizeof()
    • C++ Move Semantics
  • Basic
    • Introduction To C++
    • What is C++
    • Features of C++
    • Applications of C++
    • Best C++ Compiler
    • C++ Data Types
    • C++ Double
    • C++ unsigned int
    • User Defined Data Types in C++
    • Variables in C++
    • C++ Keywords
    • Pointers in C++
    • C++ Void Pointer
    • Function Pointer in C++
    • Iterator in C++
    • C++ Commands
    • Object in C++
    • C++ Literals
    • C++ Reference
    • C++ Undefined Reference
    • String in C++
    • C++ Programming Language (Basics)
    • C++ Identifiers
    • C++ Header Files
    • Type Casting in C++
    • C++ Formatter
  • Operators
    • C++ Operators
    • Arithmetic Operators in C++
    • Assignment Operators in C++
    • Bitwise Operators in C++
    • Relational Operators in C++
    • Boolean Operators in C++
    • Unary Operators in C++
    • C++ Operator[]
    • Operator Precedence in C++
    • C++ operator=()
  • Control Statements
    • Control Statement in C++
    • if else Statement in C++
    • Else If in C++
    • Nested if in C++
    • Continue Statement in C++
    • Break Statement in C++
    • Switch Statement in C++
    • goto Statement in C++
    • C++ Struct
    • Loops in C++
    • Do While Loop in C++
    • Nested Loop in C++
  • Array
    • Arrays in C++
    • 2D Arrays in C++
    • 3D Arrays in C++
    • Multi-Dimensional Arrays in C++
    • C++ Array Functions
    • String Array in C++
    • C++ Length of Array
    • C++ arraylist
  • Constuctor and Destructor
    • Constructor and Destructor in C++
    • Constructor in C++
    • Destructor in C++
    • Copy Constructor in C++
    • Parameterized Constructor in C++
  • Overloading and overriding
    • Overloading and Overriding in C++
    • Overloading in C++
    • Overriding in C++
    • Function Overloading in C++
    • Function Overriding in C++
    • Method Overloading in C++
  • Inhertiance
    • Types of Inheritance in C++
    • Single Inheritance in C++
    • Multiple Inheritance in C++
    • Hierarchical Inheritance in C++
    • Multilevel Inheritance in C++
    • Hybrid Inheritance in C++
  • Sorting
    • Sorting in C++ 
    • Heap Sort in C++
    • C++ Vector Sort
    • Insertion Sort in C++
    • Selection Sort in C++
    • C++ QuickSort
    • Sort string C++
  • Advanced
    • C++ namespace
    • Encapsulation in C++
    • Access Modifiers in C++
    • Abstract Class in C++
    • C++ Class and Object
    • What is Template Class in C++?
    • C++ Algorithm
    • Data Structures and Algorithms C++
    • C++ Garbage Collection
    • Virtual Keyword in C++
    • Access Specifiers in C++
    • Storage Class in C++
    • Call by Value in C++
    • Multimap in C++
    • C++ Multiset
    • C++ Lambda Expressions
    • Stack in C++
    • C++ Static
    • C++ static_cast
    • Deque in C++
    • C++ Vector Functions
    • C++ 2D Vector
    • C++ List
    • C++ Mutable
    • Enum in C++
    • Abstraction in C++
    • Signal in C++
    • C++ Queue
    • Priority Queue in C++
    • Regular Expressions in C++
    • C++ Hash Table
    • C++ Expression
    • File Handling in C++
    • C++ Stream
    • ifstream in C++
    • C++ ofstream
    • C++ fstream
    • C++ Read File
    • C++ iomanip
    • Macros in C++
    • Templates in C++
    • C++ setprecision
    • C++ Int to String
    • C++ thread( )
    • C++ Thread Pool
    • C++ thread_local
  • Programs
    • Patterns in C++
    • Star Patterns In c++
    • Swapping in C++
    • Reverse Number in C++
    • Palindrome Program in C++
    • Palindrome in C++
    • Factorial Program in C++
    • Fibonacci Series in C++
    • Square Root in C++
    • Random Number Generator in C++
    • Prime Number in C++
    • Leap Year Program in C++
    • Anagram in C++
    • Armstrong Number in C++
    • Reverse String in C++
    • Socket Programming in C++
    • Matrix Multiplication in C++
    • C++ using vs typedef
    • C++ vector vs list
    • C++ vector vs array
  • Interview question
    • C++ Interview Questions
    • Multithreading Interview Questions C++

Related Courses

C++ Training Course

Java Training Course

C Programming Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C++ Training Course Learn More