0% found this document useful (0 votes)
29 views79 pages

notes - unit 3,4,5

C++ inheritance allows one class (derived class) to inherit properties and behaviors from another class (base class), promoting code reusability. There are five types of inheritance in C++: single, multiple, hierarchical, multilevel, and hybrid. Visibility modes (public, private, protected) determine how members of the base class are accessible in the derived class, and ambiguity can arise in multiple inheritance scenarios, which can be resolved using the class resolution operator.

Uploaded by

AD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views79 pages

notes - unit 3,4,5

C++ inheritance allows one class (derived class) to inherit properties and behaviors from another class (base class), promoting code reusability. There are five types of inheritance in C++: single, multiple, hierarchical, multilevel, and hybrid. Visibility modes (public, private, protected) determine how members of the base class are accessible in the derived class, and ambiguity can arise in multiple inheritance scenarios, which can be resolved using the class resolution operator.

Uploaded by

AD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 79

C++ Inheritance

In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such a way, you can reuse, extend or
modify the attributes and behaviors which are defined in other class.

In C++, the class which inherits the members of another class is called derived class
and the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.

Advantages of C++ Inheritance


Code reusability: Now you can reuse the members of your parent class. So, there is
no need to define the member again. So, less code is required in the class.

Types Of Inheritance
C++ supports five types of inheritance:

o Single inheritance

o Multiple inheritance

o Hierarchical inheritance

o Multilevel inheritance

o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

1. class derived_class_name :: visibility-mode base_class_name


2. {
3. // body of the derived class.
4. }

Were,

derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the base class
are publicly inherited or privately inherited. It can be public or private.

base_class_name: It is the name of the base class.

o When the base class is privately inherited by the derived class, public members
of the base class become the private members of the derived class. Therefore,
the public members of the base class are not accessible by the objects of the
derived class only by the member functions of the derived class.

o When the base class is publicly inherited by the derived class, public members of
the base class also become the public members of the derived class. Therefore,
the public members of the base class are accessible by the objects of the derived
class as well as by the member functions of the base class.

Note:
o In C++, the default mode of visibility is private.

o The private members of the base class are never inherited.

C++ Single Inheritance


Single inheritance is defined as the inheritance in which a derived class is inherited
from only one base class.
Where 'A' is the base class, and 'B' is the derived class.

C++ Single Level Inheritance Example: Inheriting


Fields
When one class inherits another class, it is known as single level inheritance. Let's see
the example of single level inheritance which inherits the fields only.

1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
10. };
11. int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl;
14. cout<<"Bonus: "<<p1.bonus<<endl;
15. return 0;
16. }

Output:

Salary: 60000
Bonus: 5000
In the above example, Employee is the base class and Programmer is
the derived class.

C++ Single Level Inheritance Example: Inheriting


Methods
Let's see another example of inheritance in C++ which inherits methods only.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat () {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark () {
13. cout<<"Barking...";
14. }
15. };
16. int main(void) {
17. Dog d1;
18. d1.eat ();
19. d1.bark ();
20. return 0;
21. }

Output:

Eating...
Barking...

Let's see a simple example.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int a = 4;
6. int b = 5;
7. public:
8. int mul()
9. {
10. int c = a*b;
11. return c;
12. }
13. };
14.
15. class B: private A
16. {
17. public:
18. void display ()
19. {
20. int result = mul();
21. std::cout <<"Multiplication of a and b is: "<<result<< std::endl;
22. }
23. };
24. int main()
25. {
26. B b;
27. b.display();
28.
29. return 0;
30. }

Output:

Multiplication of a and b is : 20

In the above example, class A is privately inherited. Therefore, the mul() function of
class 'A' cannot be accessed by the object of class B. It can only be accessed by the
member function of class B.
How to make a Private Member Inheritable
The private member is not inheritable. If we modify the visibility mode by making it
public, but this takes away the advantage of data hiding.

C++ introduces a third visibility modifier, i.e., protected. The member which is
declared as protected will be accessible to all the member functions within the class as
well as the class immediately derived from it.

Visibility modes can be classified into three categories:

o Public: When the member is declared as public, it is accessible to all the


functions of the program.

o Private: When the member is declared as private, it is accessible within the


class only.

o Protected: When the member is declared as protected, it is accessible within its


own class as well as the class immediately derived from it

Visibility of Inherited Members


Base class Derived class visibility
visibility
Public Private Protected

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected


Public Public Private Protected

C++ Multilevel Inheritance


Multilevel inheritance is a process of deriving a class from another derived class.

C++ Multi Level Inheritance Example


When one class inherits another class which is further inherited by another class, it is
known as multi-level inheritance in C++. Inheritance is transitive so the last derived
class acquires all the members of all its base classes.

Let's see the example of multi-level inheritance in C++.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat ()
6. {
7. cout<<"Eating..."<<endl;
8. }
9. };
10. class Dog: public Animal
11. {
12. public:
13. void bark ()
14. {
15. cout<<"Barking..."<<endl;
16. }
17. };
18. class BabyDog: public Dog
19. {
20. public:
21. void weep ()
22. {
23. cout<<"Weeping...";
24. }
25. };
26. int main(void) {
27. BabyDog d1;
28. d1.eat ();
29. d1.bark();
30. d1.weep();
31. return 0;
32. }

Output:

Eating...
Barking...
Weeping...

C++ Multiple Inheritance


Multiple inheritance is the process of deriving a new class that inherits the attributes
from two or more classes.
Syntax of the Derived class:

1. class D : visibility B-1, visibility B-2, ?


2. {
3. // Body of the class;
4. }

Let's see a simple example of multiple inheritance.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a(int n)
9. {
10. a = n;
11. }
12. };
13.
14. class B
15. {
16. protected:
17. int b;
18. public:
19. void get_b(int n)
20. {
21. b = n;
22. }
23. };
24. class C : public A , public B
25. {
26. public:
27. void display ()
28. {
29. std::cout << "The value of a is : " <<a<< std::endl;
30. std::cout << "The value of b is : " <<b<< std::endl;
31. cout<<"Addition of a and b is: "<<a+b;
32. }
33. };
34. int main()
35. {
36. C c;
37. c.get_a(10);
38. c.get_b(20);
39. c.display();
40.
41. return 0;
42. }

Output:

The value of a is : 10
The value of b is : 20
Addition of a and b is : 30

In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.

Ambiquity Resolution in Inheritance


Ambiguity can be occurred in using the multiple inheritance when a function with the
same name occurs in more than one base class.
Let's understand this through an example:

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. void display()
7. {
8. std::cout << "Class A" << std::endl;
9. }
10. };
11. class B
12. {
13. public:
14. void display()
15. {
16. std::cout << "Class B" << std::endl;
17. }
18. };
19. class C : public A, public B
20. {
21. void view()
22. {
23. display();
24. }
25. };
26. int main()
27. {
28. C c;
29. c.display();
30. return 0;
31. }

Output:
error: reference to 'display' is ambiguous
display ();

o The above issue can be resolved by using the class resolution operator with the
function. In the above example, the derived class code can be rewritten as:

1. class C : public A, public B


2. {
3. void view()
4. {
5. A :: display(); // Calling the display() function of class A.
6. B :: display(); // Calling the display() function of class B.
7.
8. }
9. };

An ambiguity can also occur in single inheritance.

Consider the following situation:

1. class A
2. {
3. public:
4. void display()
5. {
6. cout<<?Class A?;
7. }
8. } ;
9. class B
10. {
11. public:
12. void display()
13. {
14. cout<<?Class B?;
15. }
16. } ;
In the above case, the function of the derived class overrides the method of the base
class. Therefore, call to the display() function will simply call the function defined in the
derived class. If we want to invoke the base class function, we can use the class
resolution operator.

1. int main()
2. {
3. B b;
4. b.display(); // Calling the display() function of B class.
5. b.B :: display(); // Calling the display() function defined in B class.
6. }

C++ Hybrid Inheritance


Hybrid inheritance is a combination of more than one type of inheritance.

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a()
9. {
10. std::cout << "Enter the value of 'a': " << std::endl;
11. cin>>a;
12. }
13. };
14.
15. class B : public A
16. {
17. protected:
18. int b;
19. public:
20. void get_b()
21. {
22. std::cout << "Enter the value of 'b' : " << std::endl;
23. cin>>b;
24. }
25. };
26. class C
27. {
28. protected:
29. int c;
30. public:
31. void get_c()
32. {
33. std::cout << "Enter the value of c is : " << std::endl;
34. cin>>c;
35. }
36. };
37.
38. class D : public B, public C
39. {
40. protected:
41. int d;
42. public:
43. void mul()
44. {
45. get_a();
46. get_b();
47. get_c();
48. std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
49. }
50. };
51. int main()
52. {
53. D d;
54. d.mul();
55. return 0;
56. }

Output:

Enter the value of 'a' :


10
Enter the value of 'b' :
20
Enter the value of c is :
30
Multiplication of a,b,c is : 6000

C++ Hierarchical Inheritance


Hierarchical inheritance is defined as the process of deriving more than one class from a
base class.

Syntax of Hierarchical inheritance:


1. class A
2. {
3. // body of the class A.
4. }
5. class B : public A
6. {
7. // body of class B.
8. }
9. class C : public A
10. {
11. // body of class C.
12. }
13. class D : public A
14. {
15. // body of class D.
16. }

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. class Shape // Declaration of base class.
4. {
5. public:
6. int a;
7. int b;
8. void get_data(int n,int m)
9. {
10. a= n;
11. b = m;
12. }
13. };
14. class Rectangle : public Shape // inheriting Shape class
15. {
16. public:
17. int rect_area()
18. {
19. int result = a*b;
20. return result;
21. }
22. };
23. class Triangle : public Shape // inheriting Shape class
24. {
25. public:
26. int triangle_area()
27. {
28. float result = 0.5*a*b;
29. return result;
30. }
31. };
32. int main()
33. {
34. Rectangle r;
35. Triangle t;
36. int length,breadth,base,height;
37. std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
38. cin>>length>>breadth;
39. r.get_data(length,breadth);
40. int m = r.rect_area();
41. std::cout << "Area of the rectangle is : " <<m<< std::endl;
42. std::cout << "Enter the base and height of the triangle: " << std::endl;
43. cin>>base>>height;
44. t.get_data(base,height);
45. float n = t.triangle_area();
46. std::cout <<"Area of the triangle is : " << n<<std::endl;
47. return 0;
48. }

Output:
Enter the length and breadth of a rectangle:
23
20
Area of the rectangle is : 460
Enter the base and height of the triangle:
2
5
Area of the triangle is : 5
C++ Templates
A C++ template is a powerful feature added to C++. It allows you to define the generic
classes and generic functions and thus provides support for generic programming.
Generic programming is a technique where generic types are used as parameters in
algorithms so that they can work for a variety of data types.

Templates can be represented in two ways:

o Function templates

o Class templates

Function Templates:

We can define a template for a function. For example, if we have an add() function, we
can create versions of the add function for adding the int, float or double type values.

Class Template:

We can define a template for a class. For example, a class template can be created for
the array class that can accept the array of various types such as int array, float array
or double array.

Function Template
o Generic functions use the concept of a function template. Generic functions
define a set of operations that can be applied to the various types of data.

o The type of the data that the function will operate on depends on the type of the
data passed as a parameter.
o For example, Quick sorting algorithm is implemented using a generic function, it
can be implemented to an array of integers or array of floats.

o A Generic function is created by using the keyword template. The template


defines what function will do.

Syntax of Function Template


1. template < class Ttype> ret_type func_name(parameter_list)
2. {
3. // body of function.
4. }

Where Ttype: It is a placeholder name for a data type used by the function. It is used
within the function definition. It is only a placeholder that the compiler will automatically
replace this placeholder with the actual data type.

class: A class keyword is used to specify a generic type in a template declaration.

Let's see a simple example of a function template:

1. #include <iostream>
2. using namespace std;
3. template<class T> T add(T &a,T &b)
4. {
5. T result = a+b;
6. return result;
7.
8. }
9. int main()
10. {
11. int i =2;
12. int j =3;
13. float m = 2.3;
14. float n = 1.2;
15. cout<<"Addition of i and j is :"<<add(i,j);
16. cout<<'\n';
17. cout<<"Addition of m and n is :"<<add(m,n);
18. return 0;
19. }

Output:

Addition of i and j is :5
Addition of m and n is :3.5

In the above example, we create the function template which can perform the addition
operation on any type either it can be integer, float or double.

Function Templates with Multiple Parameters


We can use more than one generic type in the template function by using the comma to
separate the list.

Syntax
1. template<class T1, class T2,.....>
2. return_type function_name (arguments of type T1, T2....)
3. {
4. // body of function.
5. }

In the above syntax, we have seen that the template function can accept any number of
arguments of a different type.

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. template<class X,class Y> void fun(X a,Y b)
4. {
5. std::cout << "Value of a is : " <<a<< std::endl;
6. std::cout << "Value of b is : " <<b<< std::endl;
7. }
8.
9. int main()
10. {
11. fun(15,12.3);
12.
13. return 0;
14. }

Output:

Value of a is : 15
Value of b is : 12.3

In the above example, we use two generic types in the template function, i.e., X and Y.

Overloading a Function Template


We can overload the generic function means that the overloaded template functions
can differ in the parameter list.

Let's understand this through a simple example:

1. #include <iostream>
2. using namespace std;
3. template<class X> void fun(X a)
4. {
5. std::cout << "Value of a is : " <<a<< std::endl;
6. }
7. template<class X,class Y> void fun(X b ,Y c)
8. {
9. std::cout << "Value of b is : " <<b<< std::endl;
10. std::cout << "Value of c is : " <<c<< std::endl;
11. }
12. int main()
13. {
14. fun(10);
15. fun(20,30.5);
16. return 0;
17. }

Output:

Value of a is : 10
Value of b is : 20
Value of c is : 30.5

In the above example, template of fun() function is overloaded.


Restrictions of Generic Functions
Generic functions perform the same operation for all the versions of a function except
the data type differs. Let's see a simple example of an overloaded function which
cannot be replaced by the generic function as both the functions have different
functionalities.

Let's understand this through a simple example:

1. #include <iostream>
2. using namespace std;
3. void fun(double a)
4. {
5. cout<<"value of a is : "<<a<<'\n';
6. }
7.
8. void fun(int b)
9. {
10. if(b%2==0)
11. {
12. cout<<"Number is even";
13. }
14. else
15. {
16. cout<<"Number is odd";
17. }
18.
19. }
20.
21. int main()
22. {
23. fun(4.6);
24. fun(6);
25. return 0;
26. }

Output:
value of a is : 4.6
Number is even

In the above example, we overload the ordinary functions. We cannot overload the
generic functions as both the functions have different functionalities. First one is
displaying the value and the second one determines whether the number is even or not.

CLASS TEMPLATE
Class Template can also be defined similarly to the Function Template. When a class
uses the concept of Template, then the class is known as generic class.

Syntax
1. template<class Ttype>
2. class class_name
3. {
4. .
5. .
6. }

Ttype is a placeholder name which will be determined when the class is instantiated.
We can define more than one generic data type using a comma-separated list. The
Ttype can be used inside the class body.

Now, we create an instance of a class

1. class_name<type> ob;

where class_name: It is the name of the class.

type: It is the type of the data that the class is operating on.

ob: It is the name of the object.

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. template<class T>
4. class A
5. {
6. public:
7. T num1 = 5;
8. T num2 = 6;
9. void add()
10. {
11. std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;
12. }
13.
14. };
15.
16. int main()
17. {
18. A<int> d;
19. d.add();
20. return 0;
21. }

Output:

Addition of num1 and num2 : 11

In the above example, we create a template for class A. Inside the main() method, we
create the instance of class A named as, 'd'.

CLASS TEMPLATE WITH MULTIPLE PARAMETERS


We can use more than one generic data type in a class template, and each generic data
type is separated by the comma.

Syntax
1. template<class T1, class T2, ......>
2. class class_name
3. {
4. // Body of the class.
5. }

Let's see a simple example when class template contains two generic data
types.
1. #include <iostream>
2. using namespace std;
3. template<class T1, class T2>
4. class A
5. {
6. T1 a;
7. T2 b;
8. public:
9. A(T1 x,T2 y)
10. {
11. a = x;
12. b = y;
13. }
14. void display()
15. {
16. std::cout << "Values of a and b are : " << a<<" ,"<<b<<std::endl;
17. }
18. };
19.
20. int main()
21. {
22. A<int,float> d(5,6.5);
23. d.display();
24. return 0;
25. }

Output:

Values of a and b are : 5,6.5

Nontype Template Arguments


The template can contain multiple arguments, and we can also use the non-type
arguments In addition to the type T argument, we can also use other types of
arguments such as strings, function names, constant expression and built-in types. Let'
s see the following example:

1. template<class T, int size>


2. class array
3. {
4. T arr[size]; // automatic array initialization.
5. };

In the above case, the nontype template argument is size and therefore, template
supplies the size of the array as an argument.

Arguments are specified when the objects of a class are created:

1. array<int, 15> t1; // array of 15 integers.


2. array<float, 10> t2; // array of 10 floats.
3. array<char, 4> t3; // array of 4 chars.

Let's see a simple example of nontype template arguments.

1. #include <iostream>
2. using namespace std;
3. template<class T, int size>
4. class A
5. {
6. public:
7. T arr[size];
8. void insert()
9. {
10. int i =1;
11. for (int j=0;j<size;j++)
12. {
13. arr[j] = i;
14. i++;
15. }
16. }
17.
18. void display()
19. {
20. for(int i=0;i<size;i++)
21. {
22. std::cout << arr[i] << " ";
23. }
24. }
25. };
26. int main()
27. {
28. A<int,10> t1;
29. t1.insert();
30. t1.display();
31. return 0;
32. }

Output:

1 2 3 4 5 6 7 8 9 10

In the above example, the class template is created which contains the nontype
template argument, i.e., size. It is specified when the object of class 'A' is created.

Points to Remember

o C++ supports a powerful feature known as a template to implement the concept


of generic programming.

o A template allows us to create a family of classes or family of functions to handle


different data types.

o Template classes and functions eliminate the code duplication of different data
types and thus makes the development easier and faster.

o Multiple parameters can be used in both class and function template.

o Template functions can also be overloaded.

o We can also use nontype arguments such as built-in or derived data types as
template arguments.

The C++ Standard Template Library


(STL)
The Standard Template Library (STL) is a set of C++ template classes to
provide common programming data structures and functions such as lists,
stacks, arrays, etc. It is a library of container classes, algorithms, and iterators.
It is a generalized library and so, its components are parameterized. A working
knowledge of template classes is a prerequisite for working with STL.

COMPONENTS OF STL CONTAINERS


Containers can be described as the objects that hold the data of the same type.
Containers are used to implement different data structures for example arrays, list,
trees, etc.

Following are the containers that give the details of all the containers as well as the
header file and the type of iterator associated with them :

Container Description Header iterator


file

vector vector is a class that creates a dynamic <vector> Random


array allowing insertions and deletions at access
the back.

list list is the sequence containers that allow <list> Bidirectional


the insertions and deletions from
anywhere.

deque deque is the double ended queue that <deque> Random


allows the insertion and deletion from access
both the ends.

set set is an associate container for storing <set> Bidirectional


unique sets.

multiset Multiset is an associate container for <set> Bidirectional


storing non- unique sets.

map Map is an associate container for storing <map> Bidirectional


unique key-value pairs, i.e. each key is
associated with only one value(one to one
mapping).

multimap multimap is an associate container for <map> Bidirectional


storing key- value pair, and each key can
be associated with more than one value.

stack It follows last in first out(LIFO). <stack> No iterator

queue It follows first in first out(FIFO). <queue> No iterator

Priority- First element out is always the highest <queue> No iterator


queue priority element.

Classification of containers :

o Sequence containers

o Associative containers

o Derived containers
ITERATOR
o Iterators are pointer-like entities used to access the individual elements in a
container.

o Iterators are moved sequentially from one element to another element. This
process is known as iterating through a container.

o Iterator contains mainly two functions:

begin(): The member function begin() returns an iterator to the first element of the
vector.

end(): The member function end() returns an iterator to the past-the-last element of a
container.

Iterator Categories
Iterators are mainly divided into five categories:
1. Input iterator:

o An Input iterator is an iterator that allows the program to read the values
from the container.

o Dereferencing the input iterator allows us to read a value from the


container, but it does not alter the value.

o An Input iterator is a one way iterator.

o An Input iterator can be incremented, but it cannot be decremented.

2. Output iterator:

o An output iterator is similar to the input iterator, except that it allows the
program to modify a value of the container, but it does not allow to read
it.

o It is a one-way iterator.

o It is a write only iterator.

3. Forward iterator:

o Forward iterator uses the ++ operator to navigate through the container.

o Forward iterator goes through each element of a container and one


element at a time.

4. Bidirectional iterator:

o A Bidirectional iterator is similar to the forward iterator, except that it also


moves in the backward direction.

o It is a two way iterator.

o It can be incremented as well as decremented.

5. Random Access Iterator:

o Random access iterator can be used to access the random element of a


container.
o Random access iterator has all the features of a bidirectional iterator, and
it also has one more additional feature, i.e., pointer addition. By using the
pointer addition operation, we can access the random element of a
container.

Operations supported by iterators

iterator Element Read Write Increment Comparison


access operation

input -> v= ++ ==,!=


*p

output *p = ++
v

forward -> v= *p = ++ ==,!=


*p v

Bidirectional -> v= *p = ++,-- ==,!=


*p v

Random ->,[ ] v= *p = ++,--, ==,!=,<,>,<=,>=


access *p v +,-,+=,--
=

Algorithms
Algorithms are the functions used across a variety of containers for processing its
contents.

Points to Remember:

o Algorithms provide approx 60 algorithm functions to perform the complex


operations.
o Standard algorithms allow us to work with two distinct types of the container at
the same time.

o Algorithms are not the member functions of a container, but they are the
standalone template functions.

o Algorithms save a lot of time and effort.

o If we want to access the STL algorithms, we must include the <algorithm>


header file in our program.

STL algorithms can be categorized as:

o Nonmutating algorithms: Nonmutating algorithms are the algorithms that do


not alter any value of a container object nor do they change the order of the
elements in which they appear. These algorithms can be used for all the
container objects, and they make use of the forward iterators.
o Mutating algorithms: Mutating algorithms are the algorithms that can be used
to alter the value of a container. They can also be used to change the order of
the elements in which they appear.

o Sorting algorithms: Sorting algorithms are the modifying algorithms used to


sort the elements in a container.

o Set algorithms: Set algorithms are also known as sorted range algorithm. This
algorithm is used to perform some function on a container that greatly improves
the efficiency of a program.

o Relational algorithms: Relational algorithms are the algorithms used to work


on the numerical data. They are mainly designed to perform the mathematical
operations to all the elements in a container.

C++ Vector
A vector is a sequence container class that implements dynamic array, means size
automatically changes when appending elements. A vector stores the elements in
contiguous memory locations and allocates the memory as needed at run time.

Difference between vector and array


An array follows static approach, means its size cannot be changed during run time
while vector implements dynamic array means it automatically resizes itself when
appending elements.

Syntax
Consider a vector 'v1'. Syntax would be:

1. vector<object_type> v1;
Example
Let's see a simple example.

1. #include<iostream>
2. #include<vector>
3. using namespace std;
4. int main()
5. {
6. vector<string> v1;
7. v1.push_back("javaTpoint ");
8. v1.push_back("tutorial");
9. for(vector<string>::iterator itr=v1.begin();itr!=v1.end();++itr)
10. cout<<*itr;
11. return 0;
12. }

Output:

javaTpoint tutorial

In this example, vector class has been used to display the string.

C++ Vector Functions


Function Description

at() It provides a reference to an element.

back() It gives a reference to the last element.

front() It gives a reference to the first element.

swap() It exchanges the elements between two vectors.

push_back() It adds a new element at the end.

pop_back() It removes a last element from the vector.

empty() It determines whether the vector is empty or not.

insert() It inserts new element at the specified position.

erase() It deletes the specified element.


resize() It modifies the size of the vector.

clear() It removes all the elements from the vector.

size() It determines a number of elements in the vector.

capacity() It determines the current capacity of the vector.

assign() It assigns new values to the vector.

operator=() It assigns new values to the vector container.

operator[]() It access a specified element.

end() It refers to the past-lats-element in the vector.

emplace() It inserts a new element just before the position pos.

emplace_back() It inserts a new element at the end.

rend() It points the element preceding the first element of the


vector.

rbegin() It points the last element of the vector.

begin() It points the first element of the vector.

max_size() It determines the maximum size that vector can hold.

cend() It refers to the past-last-element in the vector.

cbegin() It refers to the first element of the vector.


crbegin() It refers to the last character of the vector.

crend() It refers to the element preceding the first element of


the vector.

data() It writes the data of the vector into an array.

shrink_to_fit() It reduces the capacity and makes it equal to the size


of the vector.

Certain functions associated with the vector are:


Iterators
1. begin() – Returns an iterator pointing to the first element in the vector
2. end() – Returns an iterator pointing to the theoretical element that follows the
last element in the vector
3. rbegin() – Returns a reverse iterator pointing to the last element in the vector
(reverse beginning). It moves from last to first element
4. rend() – Returns a reverse iterator pointing to the theoretical element
preceding the first element in the vector (considered as reverse end)
5. cbegin() – Returns a constant iterator pointing to the first element in the
vector.
6. cend() – Returns a constant iterator pointing to the theoretical element that
follows the last element in the vector.
7. crbegin() – Returns a constant reverse iterator pointing to the last element in
the vector (reverse beginning). It moves from last to first element
8. crend() – Returns a constant reverse iterator pointing to the theoretical
element preceding the first element in the vector (considered as reverse
end)

// C++ program to illustrate the

// iterators in vector
#include <iostream>

#include <vector>

using namespace std;

int main()

vector<int> g1;

for (int i = 1; i <= 5; i++)

g1.push_back(i);

cout << "Output of begin and end: ";

for (auto i = g1.begin(); i != g1.end(); ++i)

cout << *i << " ";

cout << "\nOutput of cbegin and cend: ";

for (auto i = g1.cbegin(); i != g1.cend(); ++i)

cout << *i << " ";


cout << "\nOutput of rbegin and rend: ";

for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir)

cout << *ir << " ";

cout << "\nOutput of crbegin and crend : ";

for (auto ir = g1.crbegin(); ir != g1.crend(); ++ir)

cout << *ir << " ";

return 0;

Output:
Output of begin and end: 1 2 3 4 5
Output of cbegin and cend: 1 2 3 4 5
Output of rbegin and rend: 5 4 3 2 1
Output of crbegin and crend : 5 4 3 2 1

Capacity
1. size() – Returns the number of elements in the vector.
2. max_size() – Returns the maximum number of elements that the vector can
hold.
3. capacity() – Returns the size of the storage space currently allocated to the
vector expressed as number of elements.
4. resize(n) – Resizes the container so that it contains ‘n’ elements.
5. empty() – Returns whether the container is empty.
6. shrink_to_fit() – Reduces the capacity of the container to fit its size and
destroys all elements beyond the capacity.
7. reserve() – Requests that the vector capacity be at least enough to contain n
elements.

// C++ program to illustrate the

// capacity function in vector

#include <iostream>

#include <vector>

using namespace std;

int main()

vector<int> g1;

for (int i = 1; i <= 5; i++)

g1.push_back(i);

cout << "Size : " << g1.size();

cout << "\nCapacity : " << g1.capacity();

cout << "\nMax_Size : " << g1.max_size();


// resizes the vector size to 4

g1.resize(4);

// prints the vector size after resize()

cout << "\nSize : " << g1.size();

// checks if the vector is empty or not

if (g1.empty() == false)

cout << "\nVector is not empty";

else

cout << "\nVector is empty";

// Shrinks the vector

g1.shrink_to_fit();

cout << "\nVector elements are: ";

for (auto it = g1.begin(); it != g1.end(); it++)

cout << *it << " ";


return 0;

Output:
Size : 5
Capacity : 8
Max_Size : 4611686018427387903
Size : 4
Vector is not empty
Vector elements are: 1 2 3 4
Element access:
1. reference operator [g] – Returns a reference to the element at position ‘g’ in
the vector
2. at(g) – Returns a reference to the element at position ‘g’ in the vector
3. front() – Returns a reference to the first element in the vector
4. back() – Returns a reference to the last element in the vector
5. data() – Returns a direct pointer to the memory array used internally by the
vector to store its owned elements.

// C++ program to illustrate the

// element accesser in vector

#include <bits/stdc++.h>

using namespace std;

int main()

vector<int> g1;
for (int i = 1; i <= 10; i++)

g1.push_back(i * 10);

cout << "\nReference operator [g] : g1[2] = " << g1[2];

cout << "\nat : g1.at(4) = " << g1.at(4);

cout << "\nfront() : g1.front() = " << g1.front();

cout << "\nback() : g1.back() = " << g1.back();

// pointer to the first element

int* pos = g1.data();

cout << "\nThe first element is " << *pos;

return 0;

Output:
Reference operator [g] : g1[2] = 30
at : g1.at(4) = 50
front() : g1.front() = 10
back() : g1.back() = 100
The first element is 10
Modifiers:
1. assign() – It assigns new value to the vector elements by replacing old ones
2. push_back() – It push the elements into a vector from the back
3. pop_back() – It is used to pop or remove elements from a vector from the
back.
4. insert() – It inserts new elements before the element at the specified position
5. erase() – It is used to remove elements from a container from the specified
position or range.
6. swap() – It is used to swap the contents of one vector with another vector of
same type. Sizes may differ.
7. clear() – It is used to remove all the elements of the vector container
8. emplace() – It extends the container by inserting new element at position
9. emplace_back() – It is used to insert a new element into the vector
container, the new element is added to the end of the vector
.

// C++ program to illustrate the

// Modifiers in vector

#include <bits/stdc++.h>

#include <vector>

using namespace std;

int main()

// Assign vector
vector<int> v;

// fill the array with 10 five times

v.assign(5, 10);

cout << "The vector elements are: ";

for (int i = 0; i < v.size(); i++)

cout << v[i] << " ";

// inserts 15 to the last position

v.push_back(15);

int n = v.size();

cout << "\nThe last element is: " << v[n - 1];

// removes last element

v.pop_back();

// prints the vector

cout << "\nThe vector elements are: ";


for (int i = 0; i < v.size(); i++)

cout << v[i] << " ";

// inserts 5 at the beginning

v.insert(v.begin(), 5);

cout << "\nThe first element is: " << v[0];

// removes the first element

v.erase(v.begin());

cout << "\nThe first element is: " << v[0];

// inserts at the beginning

v.emplace(v.begin(), 5);

cout << "\nThe first element is: " << v[0];

// Inserts 20 at the end

v.emplace_back(20);
n = v.size();

cout << "\nThe last element is: " << v[n - 1];

// erases the vector

v.clear();

cout << "\nVector size after erase(): " << v.size();

// two vector to perform swap

vector<int> v1, v2;

v1.push_back(1);

v1.push_back(2);

v2.push_back(3);

v2.push_back(4);

cout << "\n\nVector 1: ";

for (int i = 0; i < v1.size(); i++)

cout << v1[i] << " ";

cout << "\nVector 2: ";


for (int i = 0; i < v2.size(); i++)

cout << v2[i] << " ";

// Swaps v1 and v2

v1.swap(v2);

cout << "\nAfter Swap \nVector 1: ";

for (int i = 0; i < v1.size(); i++)

cout << v1[i] << " ";

cout << "\nVector 2: ";

for (int i = 0; i < v2.size(); i++)

cout << v2[i] << " ";

Output:
The vector elements are: 10 10 10 10 10
The last element is: 15
The vector elements are: 10 10 10 10 10
The first element is: 5
The first element is: 10
The first element is: 5
The last element is: 20
Vector size after erase(): 0
Vector 1: 1 2
Vector 2: 3 4
After Swap
Vector 1: 3 4
Vector 2: 1 2
C++ stack
In computer science we go for working on a large variety of programs. Each of them has
their own domain and utility. Based on the purpose and environment of the program
creation, we have a large number of data structures available to choose from. One of
them is 'stack'. Before discussing about this data type let us take a look at its syntax.

Syntax
1. template<class T, class Container = deque<T> > class stack;

This data structure works on the LIFO technique, where LIFO stands for Last In First Out.
The element which was first inserted will be extracted at the end and so on. There is an
element called as 'top' which is the element at the upper most position. All the insertion
and deletion operations are made at the top element itself in the stack.

Stacks in the application areas are implied as the container adaptors.

The containers should have a support for the following list of operations:

o empty

o size

o back

o push_back

o pop_back

Functions
With the help of functions, an object or variable can be played with in the field of
programming. Stacks provide a large number of functions that can be used or
embedded in the programs. A list of the same is given below:

Function Description

(constructor) The function is used for the construction of a stack container.

empty The function is used to test for the emptiness of a stack. If the stack is
empty the function returns true else false.
size The function returns the size of the stack container, which is a measure
of the number of elements stored in the stack.

top The function is used to access the top element of the stack. The
element plays an important role as all the insertion and deletion
operations are performed at the top element.

push The function is used for the insertion of a new element at the top of the
stack.

pop The function is used for the deletion of element, the element in the
stack is deleted from the top.

emplace The function is used for insertion of new elements in the stack above
the current top element.

swap The function is used for interchanging the contents of two containers in
reference.

relational The non member function specifies the relational operators that are
operators needed for the stacks.

uses As the name suggests the non member function uses the allocator for
allocator<stack the stacks.
>

Example: A simple program to show the use of basic stack


functions.
1. #include <iostream>
2. #include <stack>
3. using namespace std;
4. void newstack(stack <int> ss)
5. {
6. stack <int> sg = ss;
7. while (!sg.empty())
8. {
9. cout << '\t' << sg.top();
10. sg.pop();
11. }
12. cout << '\n';
13. }
14. int main ()
15. {
16. stack <int> newst;
17. newst.push(55);
18. newst.push(44);
19. newst.push(33);
20. newst.push(22);
21. newst.push(11);
22.
23. cout << "The stack newst is : ";
24. newstack(newst);
25. cout << "\n newst.size() : " << newst.size();
26. cout << "\n newst.top() : " << newst.top();
27. cout << "\n newst.pop() : ";
28. newst.pop();
29. newstack(newst);
30. return 0;
31. }

Output:

The stack newst is : 11 22 33 44 55

newst.size() : 5
newst.top() : 11
newst.pop() : 22 33 44 55
#include <iostream>

#include <stack>

using namespace std;

int main() {

stack<int> stack;

stack.push(21);

stack.push(22);

stack.push(24);

stack.push(25);

stack.pop();

stack.pop();

while (!stack.empty()) {

cout << ' ' << stack.top();

stack.pop();

Output
22 21
Code Explanation:
1. Include the iostream header file or <bits/stdc++.h> in our code to use its
functions.
2. Include the stack header file in our code to use its functions if already
included <bits/stdc++.h> then no need of stack header file because it has
already inbuilt function in it.
3. Include the std namespace in our code to use its classes without calling it.
4. Call the main() function. The program logic should be added within this
function.
5. Create a stack stack to store integer values.
6. Use the push() function to insert the value 21 into the stack.
7. Use the push() function to insert the value 22 into the stack.
8. Use the push() function to insert the value 24 into the stack.
9. Use the push() function to insert the value 25 into the stack.
10. Use the pop() function to remove the top element from the stack, that is,
25. The top element now becomes 24.
11. Use the pop() function to remove the top element from the stack, that is,
24. The top element now becomes 22.
12. Use a while loop and empty() function to check whether the stack is NOT
empty. The ! is the NOT operator.
13. Printing the current contents of the stack on the console.
14. Call the pop() function on the stack.
15. End of the body of the while loop.
16. End of the main() function body.

Member Functions of Stack Container

Following are some of the most commonly used functions of


Stack container in STL:
push function

push() is used to insert the element in the stack, the


elements are inserted at the top of the stack.
#include <iostream>

#include <stack>

using namespace std;

int main ()

stack<int> s; // creates an empty stack of integer s

s.push(2); // pushes 2 in the stack , now top =2

s.push(3); // pushes 3 in the stack , now top =3


}

pop function

This method is used to removes single element from the


stack. It reduces the size of the stack by 1. The element
removed is always the topmost element of the stack (most
recently added element) . The pop() method does not return
anything.

top function

This method returns the topmost element of the stack. Note


that this method returns the element, not removes it, unlike
pop().

SYNTAX: top()
size and empty functions

size() returns the number of elements present in the stack,


whereas empty() checks if the stack is empty or not. empty
returns true if the stack is empty else false is returned.
swap function

This method swaps the elements of the two stacks.


#include <iostream>

#include <stack>

using namespace std;

int main ()

stack<int> s;

// pushing elements into stack

s.push(2);

s.push(3);

s.push(4);

cout << s.top(); // prints 4, as 4 is the topmost element

cout << s.size(); // prints 3, as there are 3 elements in


}
C++ List
o List is a contiguous container while vector is a non-contiguous container i.e list
stores the elements on a contiguous memory and vector stores on a non-
contiguous memory.

o Insertion and deletion in the middle of the vector is very costly as it takes lot of
time in shifting all the elements. Linklist overcome this problem and it is
implemented using list container.

o List supports a bidirectional and provides an efficient way for insertion and
deletion operations.

o Traversal is slow in list as list elements are accessed sequentially while vector
supports a random access.

Template for list


1. #include<iostream>
2. #include<list>
3. using namespace std;
4. int main()
5. {
6. list<int> l;
7. }

It creates an empty list of integer type values.

List can also be initalised with the parameters.

1. #include<iostream>
2. #include<list>
3. using namespace std;
4. int main()
5. {
6. list<int> l{1,2,3,4};
7. }

List can be initialised in two ways.


1. list<int> new_list{1,2,3,4};
2. or
3. list<int> new_list = {1,2,3,4};

C++ List Functions


Following are the member functions of the list:

Method Description

insert() It inserts the new element before the position pointed by the
iterator.

push_back() It adds a new element at the end of the vector.

push_front() It adds a new element to the front.

pop_back() It deletes the last element.

pop_front() It deletes the first element.

empty() It checks whether the list is empty or not.

size() It finds the number of elements present in the list.

max_size() It finds the maximum size of the list.

front() It returns the first element of the list.

back() It returns the last element of the list.

swap() It swaps two list when the type of both the list are same.

reverse() It reverses the elements of the list.

sort() It sorts the elements of the list in an increasing order.

merge() It merges the two sorted list.

splice() It inserts a new list into the invoking list.


unique() It removes all the duplicate elements from the list.

resize() It changes the size of the list container.

assign() It assigns a new element to the list container.

emplace() It inserts a new element at a specified position.

emplace_back() It inserts a new element at the end of the vector.

emplace_front() It inserts a new element at the beginning of the list.

Syntax for creating a new linked list using list template is:
#include <iostream>

#include <list>

int main()

std::list<int> l;

/* Creates a new empty linked list l */

Similar to vector and array, lists can also be intialised with


parameters,
#include <iostream>

#include <list>

using namespace std;


int main()

std::list<int> l{1,2,3};

/* Creates a new linked list l */

Here are some more ways by which we can initialize our list:
#include <iostream>

#include <list>

int main()

list<int> myList{1,2,3};

/* creates list with 1,2,3 in it */

list<int> myNewList = 1;

/* create list myNewList of integer


and copies value of 1 into it*/

Member Functions of List Container

insert function

This method, as the name suggests, inserts an element at


specific position, in a list. There are 3 variations of insert(),
they are as follows :

 insert(iterator, element) : inserts element in the list before


the position pointed by the iterator.
 insert(iterator, count, element) : inserts element in the list
before the position pointed by
the iterator, count number of times.
 insert(iterator, start_iterator, end_iterator): insert the element
pointed by start_iterator to the element pointed
by end_iterator before the position pointed by iterator
#include <iostream>

#include <list>

using namespace std;

int main()

list<int> l = {1,2,3,4,5};

list<int>::iterator it = l.begin();
l.insert (it+1, 100); // insert 100 before 2 position

/* now the list is 1 100 2 3 4 5 */

list<int> new_l = {10,20,30,40}; // new list

new_l.insert (new_l.begin(), l.begin(), l.end());

/*

insert elements from beginning of list l to end of list l

before 1 position in list new_l */

/* now the list new_l is 1 100 2 3 4 5 10 20 30 40 */

l.insert(l.begin(), 5, 10); // insert 10 before beginning 5


times

/* now l is 10 10 10 10 10 1 100 2 3 4 5 */

return 0;

push_back and push_front functions

push_back(element) method is used to push elements into a list


from the back.
push_front(element) method is used to push elements into a list
from the front.

#include <iostream>

#include <list>

using namespace std;

int main()

list<int> l{1,2,3,4,5};
l.push_back(6);

l.push_back(7);

/* now the list becomes 1,2,3,4,5,6,7 */

l.push_front(8);

l.push_front(9);

/* now the list becomes 9,8,1,2,3,4,5,6,7 */

pop_back and pop_front functions

pop_front() removes first element from the start of the list.


While pop_back() removes first element from the end of the
list.
#include <iostream>

#include <list>

using namespace std;

int main()

list<int> l{1,2,3,4,5};

l.pop_back()();

/* now the list becomes 1,2,3,4 */


l.pop_front()();

/* now the list becomes 2,3,4 */

empty function

This method returns true if the list is empty else returns false.
size function

This method can be used to find the number of elements


present in the list.
front and back function

front() is used to get the first element of the list from the start
while back() is used to get the first element of the list from the
back.
swap function

Swaps two list, if there is exception thrown while swapping


any element, swap() throws exception. Both lists which are to
be swapped must be of the same type, i.e you can’t swap list
of an integer with list of strings.
reverse function

This method can be used to reverse a list completely.


#include <iostream>

#include <list>

using namespace std;


int main()

list<int> l{1,2,3,4,5};

l.reverse();

/* now the list becomes 5,4,3,2,1 */

sort function

sort() method sorts the given list. It does not create new
sorted list but changes the position of elements within an
existing list to sort it. This method has two variations :

 sort() : sorts the elements of the list in ascending order,


the element of the list should by numeric for this
function.
 sort(compare_function) : This type of sort() is used when we
have to alter the method of sorting. Its very helpful for
the elements that are not numeric. We can define how
we want to sort the list elements in compare_funtion. For
example, list of strings can be sorted by the length of
the string, it can also be used for sorting in descending
order.
#include <iostream>

#include <list>

using namespace std;


bool compare_function( string& s1 , string& s2 )

return ( s1.length() > s2.length() );

int main()

list<int> list1 = {2,4,5,6,1,3};

list<string> list2 = {"h", "hhh", "hh"};

list1.sort();

/* list1 is now 1 2 3 4 5 6 */

list2.sort(compare_function);

/* list2 is now h hh hhh */

splice function

splice() method transfers the elements from one list to


another. There are three versions of splice :

 splice(iterator, list_name) : Transfers complete


list list_name at position pointed by the iterator.
 splice(iterator, list_name, iterator_pos) : Transfer elements
pointed by iterator_pos from list_name at position
pointed by iterator.
 splice(iterator, list_name, itr_start, itr_end) : Transfer range
specified by itr_start and itr_end from list_name at
position pointed by iterator.
#include <iostream>

#include <list>

using namespace std;

int main ()

list<int> list1 = {1,2,3,4};

list<int> list2 = {5,6,7,8};

list<int>::iterator it;

it = list1.begin();

++it; //pointing to second position

list1.splice(it, list2);

/* transfer all elements of list2 at position 2 in list1 */

/* now list1 is 1 5 6 7 8 2 3 4 and list2 is empty */

list2.splice(list2.begin(), list1, it);


/* transfer element pointed by it in list1 to the beginning
of list2 */

/* list2 is now 5 and list1 is 1 6 7 8 2 3 4*/

return 0;

merge function

Merges two sorted list. It is mandatory that both the list


should be sorted first. merge() merges the two list such that
each element is placed at its proper position in the resulting
list. Syntax for merge is list1.merge(list2).

The list that is passed as parameter does not get deleted and
the list which calls the merge() becomes the merged list
#include <iostream>

#include <list>

using namespace std;

int main ()

list<int> list1 = {1,3,5,7,9};

list<int> list2 = {2,4,6,8,10};

/* both the lists are sorted. In case they are not ,

first they should be sorted by sort function() */


list1.merge(list2);

/* list list1 is now 1,2,3,4,5,6,7,8,9,10 */

cout << list1.size() << endl; // prints 10

}
C++ map function
Maps are part of the C++ STL (Standard Template Library). Maps are the associative
containers that store sorted key-value pair, in which each key is unique and it can be
inserted or deleted but cannot be altered. Values associated with keys can be changed.

For example: A map of Employees where employee ID is the key and name is the
value can be represented as:

Keys Values

101 Nikita

102 Robin

103 Deep

104 John

Syntax
1. template < class Key, // map::key_type
2. class T, // map::mapped_type
3. class Compare = less<Key>, // map::key_compare
4. class Alloc = allocator<pair<const Key,T> > // map::allocator_type
5. > class map;
Parameter

key: The key data type to be stored in the map.

type: The data type of value to be stored in the map.

compare: A comparison class that takes two arguments of the same type bool and
returns a value. This argument is optional and the binary predicate less<"key"> is the
default value.

alloc: Type of the allocator object. This argument is optional and the default value is
allocator .
Creating a map
Maps can easily be created using the following statement:

1. typedef pair<const Key, T> value_type;

The above form will use to create a map with key of type Key type and value of
type value type. One important thing is that key of a map and corresponding values
are always inserted as a pair, you cannot insert only key or just a value in a map.

Example 1
1. #include <string.h>
2. #include <iostream>
3. #include <map>
4. #include <utility>
5. using namespace std;
6. int main()
7. {
8. map<int, string> Employees;
9. // 1) Assignment using array index notation
10. Employees[101] = "Nikita";
11. Employees[105] = "John";
12. Employees[103] = "Dolly";
13. Employees[104] = "Deep";
14. Employees[102] = "Aman";
15. cout << "Employees[104]=" << Employees[104] << endl << endl;
16. cout << "Map size: " << Employees.size() << endl;
17. cout << endl << "Natural Order:" << endl;
18. for( map<int,string>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii)
19. {
20. cout << (*ii).first << ": " << (*ii).second << endl;
21. }
22. cout << endl << "Reverse Order:" << endl;
23. for( map<int,string>::reverse_iterator ii=Employees.rbegin(); ii!=Employees.rend();
++ii)
24. {
25. cout << (*ii).first << ": " << (*ii).second << endl;
26. }
27. }

Output:

Employees[104]=Deep

Map size: 5

Natural Order:
101: Nikita
102: Aman
103: Dolly
104: Deep
105: John

Reverse Order:
105: John
104: Deep
103: Dolly
102: Aman
101: Nikita

Member Functions
Below is the list of all member functions of map:

Constructor/Destructor
Functions Description

constructors Construct map

destructors Map destructor

operator= Copy elements of the map to another map.

Iterators
Functions Description

begin Returns an iterator pointing to the first element in the map.


cbegin Returns a const iterator pointing to the first element in the map.

end Returns an iterator pointing to the past-end.

cend Returns a constant iterator pointing to the past-end.

rbegin Returns a reverse iterator pointing to the end.

rend Returns a reverse iterator pointing to the beginning.

crbegin Returns a constant reverse iterator pointing to the end.

crend Returns a constant reverse iterator pointing to the beginning.

Capacity
Functions Description

empty Returns true if map is empty.

size Returns the number of elements in the map.

max_size Returns the maximum size of the map.

Element Access
Functions Description

operator[] Retrieve the element with given key.

at Retrieve the element with given key.


Modifiers
Functions Description

insert Insert element in the map.

erase Erase elements from the map.

swap Exchange the content of the map.

clear Delete all the elements of the map.

emplace Construct and insert the new elements into the map.

emplace_hint Construct and insert new elements into the map by hint.

Observers
Functions Description

key_comp Return a copy of key comparison object.

value_comp Return a copy of value comparison object.

Operations
Functions Description

find Search for an element with given key.

count Gets the number of elements matching with given key.

lower_bound Returns an iterator to lower bound.


upper_bound Returns an iterator to upper bound.

equal_range Returns the range of elements matches with given key.

Allocator
Functions Description

get_allocator Returns an allocator object that is used to construct the map.

Non-Member Overloaded Functions


Functions Description

operator== Checks whether the two maps are equal or not.

operator!= Checks whether the two maps are equal or not.

operator< Checks whether the first map is less than other or not.

operator<= Checks whether the first map is less than or equal to other or not.

operator> Checks whether the first map is greater than other or not.

operator>= Checks whether the first map is greater than equal to other or not.

swap() Exchanges the element of two maps.

You might also like