notes - unit 3,4,5
notes - unit 3,4,5
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.
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.
Were,
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.
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.
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.
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...
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.
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...
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.
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 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. }
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:
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.
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.
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.
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.
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.
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.
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
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.
1. class_name<type> ob;
type: It is the type of the data that the class is operating on.
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:
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'.
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:
In the above case, the nontype template argument is size and therefore, template
supplies the size of the array as an argument.
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 Template classes and functions eliminate the code duplication of different data
types and thus makes the development easier and faster.
o We can also use nontype arguments such as built-in or derived data types as
template arguments.
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 :
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.
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.
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.
3. Forward iterator:
4. Bidirectional iterator:
output *p = ++
v
Algorithms
Algorithms are the functions used across a variety of containers for processing its
contents.
Points to Remember:
o Algorithms are not the member functions of a container, but they are the
standalone template functions.
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.
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.
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.
// iterators in vector
#include <iostream>
#include <vector>
int main()
vector<int> g1;
g1.push_back(i);
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.
#include <iostream>
#include <vector>
int main()
vector<int> g1;
g1.push_back(i);
g1.resize(4);
if (g1.empty() == false)
else
g1.shrink_to_fit();
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.
#include <bits/stdc++.h>
int main()
vector<int> g1;
for (int i = 1; i <= 10; i++)
g1.push_back(i * 10);
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
.
// Modifiers in vector
#include <bits/stdc++.h>
#include <vector>
int main()
// Assign vector
vector<int> v;
v.assign(5, 10);
v.push_back(15);
int n = v.size();
cout << "\nThe last element is: " << v[n - 1];
v.pop_back();
v.insert(v.begin(), 5);
v.erase(v.begin());
v.emplace(v.begin(), 5);
v.emplace_back(20);
n = v.size();
cout << "\nThe last element is: " << v[n - 1];
v.clear();
v1.push_back(1);
v1.push_back(2);
v2.push_back(3);
v2.push_back(4);
// Swaps v1 and v2
v1.swap(v2);
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.
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
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.
>
Output:
newst.size() : 5
newst.top() : 11
newst.pop() : 22 33 44 55
#include <iostream>
#include <stack>
int main() {
stack<int> stack;
stack.push(21);
stack.push(22);
stack.push(24);
stack.push(25);
stack.pop();
stack.pop();
while (!stack.empty()) {
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.
#include <stack>
int main ()
pop function
top function
SYNTAX: top()
size and empty functions
#include <stack>
int main ()
stack<int> s;
s.push(2);
s.push(3);
s.push(4);
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.
1. #include<iostream>
2. #include<list>
3. using namespace std;
4. int main()
5. {
6. list<int> l{1,2,3,4};
7. }
Method Description
insert() It inserts the new element before the position pointed by the
iterator.
swap() It swaps two list when the type of both the list are same.
Syntax for creating a new linked list using list template is:
#include <iostream>
#include <list>
int main()
std::list<int> l;
#include <list>
std::list<int> l{1,2,3};
Here are some more ways by which we can initialize our list:
#include <iostream>
#include <list>
int main()
list<int> myList{1,2,3};
list<int> myNewList = 1;
insert function
#include <list>
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 l is 10 10 10 10 10 1 100 2 3 4 5 */
return 0;
#include <iostream>
#include <list>
int main()
list<int> l{1,2,3,4,5};
l.push_back(6);
l.push_back(7);
l.push_front(8);
l.push_front(9);
#include <list>
int main()
list<int> l{1,2,3,4,5};
l.pop_back()();
empty function
This method returns true if the list is empty else returns false.
size 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
#include <list>
list<int> l{1,2,3,4,5};
l.reverse();
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 :
#include <list>
int main()
list1.sort();
/* list1 is now 1 2 3 4 5 6 */
list2.sort(compare_function);
splice function
#include <list>
int main ()
list<int>::iterator it;
it = list1.begin();
list1.splice(it, list2);
return 0;
merge function
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>
int main ()
}
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
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:
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
Iterators
Functions Description
Capacity
Functions Description
Element Access
Functions Description
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
Operations
Functions Description
Allocator
Functions Description
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.