C++ Programming Code Examples
C++ > Visual C++ 5.0 Standard C++ Library Code Examples
Algorithm make heap - A heap is a sequence of elements organized like a binary tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
Algorithm make heap - A heap is a sequence of elements organized like a binary tree
make_heap
Header
<algorithm>
template<class RandomAccessIterator> inline
void make_heap(RandomAccessIterator first, RandomAccessIterator last)
A heap is a sequence of elements organized like a binary tree. Each heap element corresponds to a tree node. The first value in the sequence [first..last) is the root, and is the largest value in the heap. Every element in the heap satisfies the following: Every element is less than or equal to its parent. The largest element is stored in the root, and all children hold progressively smaller values. The make_heap function converts the range [first..last) into a heap. The non-predicate versions of the heap functions use the operator< for comparisons.
template<class RandomAccessIterator, class Compare> inline
void make_heap(RandomAccessIterator first, RandomAccessIterator last, Compare compare)
A heap is a sequence of elements organized like a binary tree. Each heap element corresponds to a tree node. The first value in the sequence [first..last) is the root, and is ordered by the predicate. For example, if the predicate is greater, every element in the heap satisfies the following: Every element is greater than or equal to its parent. The smallest element is stored in the root, and all children hold progressively larger values. The make_heap function converts the range [first..last) into a heap. The predicate versions of the heap functions use the compare function for comparisons.
Samples
Sample for Non-Predicate Version
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 10 ;
Numbers[4] = 30 ;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// convert Numbers into a heap
make_heap(Numbers.begin(), Numbers.end()) ;
cout << "After calling make_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// sort the heapified sequence Numbers
sort_heap(Numbers.begin(), Numbers.end()) ;
cout << "After calling sort_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
//insert an element in the heap
Numbers.push_back(7) ;
push_heap(Numbers.begin(), Numbers.end()) ;
// you need to call make_heap to re-assert the
// heap property
make_heap(Numbers.begin(), Numbers.end()) ;
cout << "After calling push_heap and make_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// remove the root element from the heap Numbers
pop_heap(Numbers.begin(), Numbers.end()) ;
cout << "After calling pop_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output
Numbers { 4 10 70 10 30 69 96 100 }
After calling make_heap
Numbers { 100 30 96 10 4 69 70 10 }
After calling sort_heap
Numbers { 4 10 10 30 69 70 96 100 }
After calling push_heap and make_heap
Numbers { 100 69 96 30 4 70 10 10 7 }
After calling pop_heap
Numbers { 96 69 70 30 4 7 10 10 100 }
Sample for Predicate Version
// disable warning C4786: symbol greater than 255 character,
// okay to ignore
#pragma warning(disable: 4786)
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void main()
{
const int VECTOR_SIZE = 8 ;
// Define a template class vector of int
typedef vector<int > IntVector ;
//Define an iterator for template class vector of strings
typedef IntVector::iterator IntVectorIt ;
IntVector Numbers(VECTOR_SIZE) ;
IntVectorIt it ;
// Initialize vector Numbers
Numbers[0] = 4 ;
Numbers[1] = 10;
Numbers[2] = 70 ;
Numbers[3] = 10 ;
Numbers[4] = 30 ;
Numbers[5] = 69 ;
Numbers[6] = 96 ;
Numbers[7] = 100;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// convert Numbers into a heap
make_heap(Numbers.begin(), Numbers.end(), greater<int>()) ;
cout << "After calling make_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
// sort the heapified sequence Numbers
sort_heap(Numbers.begin(), Numbers.end(), greater<int>()) ;
cout << "After calling sort_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
make_heap(Numbers.begin(), Numbers.end(), greater<int>()) ;
//insert an element in the heap
Numbers.push_back(7) ;
push_heap(Numbers.begin(), Numbers.end(), greater<int>()) ;
cout << "After calling push_heap()\n" << endl;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
//remove the root element from the heap Numbers
pop_heap(Numbers.begin(), Numbers.end(), greater<int>()) ;
cout << "After calling pop_heap\n" << endl ;
// print content of Numbers
cout << "Numbers { " ;
for(it = Numbers.begin(); it != Numbers.end(); it++)
cout << *it << " " ;
cout << " }\n" << endl ;
}
Program Output
Numbers { 4 10 70 10 30 69 96 100 }
After calling make_heap
Numbers { 4 10 69 10 30 70 96 100 }
After calling sort_heap
Numbers { 100 96 70 69 30 10 10 4 }
After calling push_heap()
Numbers { 4 7 10 30 100 10 70 96 69 }
After calling pop_heap
Numbers { 7 30 10 69 100 10 70 96 4 }
Vector Library end() Function in C++
Return iterator to end. Returns an iterator referring to the past-the-end element in the vector container. The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.
Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with vector::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as vector::begin.
Syntax for Vector end() Function in C++
#include <vector>
iterator end() noexcept;
const_iterator end() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* returns the iterator pointing to the past-the-last element of the vector container by vector::end function code example. */
// CPP program to illustrate implementation of begin() function
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// declaration of vector container
vector<string> myvector{ "This", "is",
"HappyCodings" };
// using begin() to print vector
for (auto it = myvector.begin();
it != myvector.end(); ++it)
cout << ' ' << *it;
return 0;
}
Algorithm Library pop_heap() Function in C++
Pop element from heap range. Rearranges the elements in the heap range [first,last) in such a way that the part considered a heap is shortened by one: The element with the highest value is moved to (last-1). pop_heap() function is used to delete the maximum element of the heap. The size of heap is decreased by 1. The heap elements are reorganised accordingly after this operation.
While the element with the highest value is moved from first to (last-1) (which now is out of the heap), the other elements are reorganized in such a way that the range [first,last-1) preserves the properties of a heap.
A range can be organized into a heap by calling make_heap. After that, its heap properties are preserved if elements are added and removed from it using push_heap and pop_heap, respectively.
Syntax for pop_heap() Function in C++
#include <algorithm>
//default (1)
template <class RandomAccessIterator>
void pop_heap (RandomAccessIterator first, RandomAccessIterator last);
//custom (2)
template <class RandomAccessIterator, class Compare>
void pop_heap (RandomAccessIterator first, RandomAccessIterator last,
Compare comp);
first, last
Random-access iterators to the initial and final positions of the heap to be shrank by one. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. This shall not be an empty range.
comp
Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to be less than the second in the specific strict weak ordering it defines. Unless [first,last) is a one-element heap, this argument shall be the same as used to construct the heap.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
This function does not return any value.
Complexity
Up to twice logarithmic in the distance between first and last: Compares elements and potentially swaps (or moves) them until rearranged as a shorter heap.
Data races
Some (or all) of the objects in the range [first,last) are modified.
Exceptions
Throws if any of the element comparisons, the element swaps (or moves) or the operations on iterators throws. Note that invalid arguments cause undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* C++ Algorithm pop_heap() function is used to swap the value in the position ?first? and the value in the position ?last-1? and makes the sub range [first, last-1) into a max heap. It has the effect of removing the first (largest) element from the heap defined by the range [first, last). Elements are compared using operator < for the first version or using the given binary comparison function comp for the second version. */
/* Pop element from heap range by pop_heap() function code example */
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
int main( ) {
using namespace std;
vector <int> v1;
vector <int>::iterator Iter1, Iter2;
int i;
for ( i = 1 ; i <= 9 ; i++ )
v1.push_back( i );
// Make v1 a heap with default less than ordering
random_shuffle( v1.begin( ), v1.end( ) );
make_heap ( v1.begin( ), v1.end( ) );
cout << "The heaped version of vector v1 is ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")." << endl;
// Add an element to the back of the heap
v1.push_back( 10 );
push_heap( v1.begin( ), v1.end( ) );
cout << "The reheaped v1 with 10 added is ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")." << endl;
// Remove the largest element from the heap
pop_heap( v1.begin( ), v1.end( ) );
cout << "The heap v1 with 10 removed is ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")." << endl << endl;
// Make v1 a heap with greater-than ordering with a 0 element
make_heap ( v1.begin( ), v1.end( ), greater<int>( ) );
v1.push_back( 0 );
push_heap( v1.begin( ), v1.end( ), greater<int>( ) );
cout << "The 'greater than' reheaped v1 puts the smallest "
<< "element first:\n ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")." << endl;
// Application of pop_heap to remove the smallest element
pop_heap( v1.begin( ), v1.end( ), greater<int>( ) );
cout << "The 'greater than' heaped v1 with the smallest element\n "
<< "removed from the heap is: ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")." << endl;
return 0;
}
Algorithm Library push_heap() Function in C++
Push element into heap range. push_heap() function is used to insert elements into heap. The size of the heap is increased by 1. New element is placed appropriately in the heap.
Given a heap in the range [first,last-1), this function extends the range considered a heap to [first,last) by placing the value in (last-1) into its corresponding location within it.
A range can be organized into a heap by calling make_heap. After that, its heap properties are preserved if elements are added and removed from it using push_heap and pop_heap, respectively.
Syntax for push_heap() Function in C++
#include <algorithm>
//default (1)
template <class RandomAccessIterator>
void push_heap (RandomAccessIterator first, RandomAccessIterator last);
//custom (2)
template <class RandomAccessIterator, class Compare>
void push_heap (RandomAccessIterator first, RandomAccessIterator last,
Compare comp);
first, last
Random-access iterators to the initial and final positions of the new heap range, including the pushed element. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
comp
Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to be less than the second in the specific strict weak ordering it defines. Unless [first,last) is an empty or one-element heap, this argument shall be the same as used to construct the heap.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
This function does not return any value.
Complexity
Up to logarithmic in the distance between first and last: Compares elements and potentially swaps (or moves) them until rearranged as a longer heap.
Data races
Some (or all) of the objects in the range [first,last) are modified.
Exceptions
Throws if any of the element comparisons, the element swaps (or moves) or the operations on iterators throws. Note that invalid arguments cause undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* The C++ algorithm::push_heap function is used to extend the range of max heap by one. Given that the initial range of the heap is [first, last-1), this function extends its range to [first, last) by placing the element at position (last-1) to its corresponding position. */
/* Push element into heap range by algorithm::push_heap function code example */
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main (){
vector<int> vec{10, 5, 55, 22, 27, -10};
vector<int>::iterator it;
cout<<"vec contains:";
for(it = vec.begin(); it != vec.end(); ++it)
cout<<" "<<*it;
//make the vector max heap
make_heap(vec.begin(), vec.end());
cout<<"\nAfter make_heap call, vec contains:";
for(it = vec.begin(); it != vec.end(); ++it)
cout<<" "<<*it;
//add a new element at the end of the vector
vec.push_back(50);
cout<<"\nAfter adding new element, vec contains:";
for(it = vec.begin(); it != vec.end(); ++it)
cout<<" "<<*it;
//calling push_heap function which extends
//the max heap range by 1 and rearranges
//the subrange into max heap
push_heap(vec.begin(), vec.end());
cout<<"\nAfter push_heap call, vec contains:";
for(it = vec.begin(); it != vec.end(); ++it)
cout<<" "<<*it;
return 0;
}
Algorithm Library make_heap() Function in C++
Make heap from range. Rearranges the elements in the range [first,last) in such a way that they form a heap. The C++ algorithm::make_heap function is used to rearrange the elements in the range [first,last) in such a way that they form a max heap.
A heap is a way to organize the elements of a range that allows for fast retrieval of the element with the highest value at any moment (with pop_heap), even repeatedly, while allowing for fast insertion of new elements (with push_heap).
The element with the highest value is always pointed by first. The order of the other elements depends on the particular implementation, but it is consistent throughout all heap-related functions of this header.
The elements are compared using operator< (for the first version), or comp (for the second): The element with the highest value is an element for which this would return false when compared to every other element in the range.
The standard container adaptor priority_queue calls make_heap, push_heap and pop_heap automatically to maintain heap properties for a container.
Syntax for make_heap() Function in C++
#include <algorithm>
//default (1)
template <class RandomAccessIterator>
void make_heap (RandomAccessIterator first, RandomAccessIterator last);
//custom (2)
template <class RandomAccessIterator, class Compare>
void make_heap (RandomAccessIterator first, RandomAccessIterator last,
Compare comp );
first, last
Random-access iterators to the initial and final positions of the sequence to be transformed into a heap. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. RandomAccessIterator shall point to a type for which swap is properly defined and which is both move-constructible and move-assignable.
comp
Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to be less than the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object.
This function does not return any value.
Function returns none.
Complexity
Up to linear in three times the distance between first and last: Compares elements and potentially swaps (or moves) them until rearranged as a heap.
Data races
The objects in the range [first,last) are modified.
Exceptions
Throws if any of the element comparisons, the element swaps (or moves) or the operations on iterators throws. Note that invalid arguments cause undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* make_heap() is used to transform a sequence into a heap. A heap is a data structure which points to highest( or lowest) element and making its access in O(1) time. Order of all the other elements depends upon particular implementation, but remains consistent throughout. This function is defined in the header "algorithm". */
/* Make heap from range by make_heap() function code example */
#include <iostream> // std::cout
#include <algorithm> // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector> // std::vector
using namespace std;
int main () {
int myints[] = {20,10,30,5,13};
vector<int> v(myints,myints+5);
make_heap (v.begin(),v.end());
cout << "initial max heap : " << v.front() << '\n';
pop_heap (v.begin(),v.end()); v.pop_back();
cout << "max heap after pop : " << v.front() << '\n';
v.push_back(99); push_heap (v.begin(),v.end());
cout << "max heap after push: " << v.front() << '\n';
sort_heap (v.begin(),v.end());
cout << "final sorted range :";
for (unsigned i=0; i<v.size(); i++)
cout << ' ' << v[i];
cout << '\n';
return 0;
}
Functions in C++
The function in C++ language is also known as procedure or subroutine in other programming languages. To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability. Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check...
Defining a Function in C++
return-type function-name(parameter1, parameter2, ...)
{
// function-body
}
return type
suggests what the function will return. It can be int, char, some pointer or even a class object. There can be functions which does not return anything, they are mentioned with void.
name
Function name is the name of the function, using the function name it is called.
parameters
Parameters are variables to hold values of arguments passed while function is called. A function may or may not contain parameter list.
body
Function body is the part where the code statements are written.
Function declaration, is done to tell the compiler about the existence of the function. Function's return type, its name & parameter list is mentioned. Function body is written in its definition.
Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them:
• Call by Value: In this calling technique we pass the values of arguments which are stored or copied into the formal parameters of functions. Hence, the original values are unchanged only the parameters inside function changes.
• Call by Reference: In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as a reference or a pointer, in both the case they will change the values of the original variable.
Advantage of Functions
• Code Reusability: By creating functions in C++, you can call it many times. So we don't need to write the same code again and again.
• Code optimization: It makes the code optimized, we don't need to write much code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* function with parameters in C++ language */
// program to print a text
#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main() {
int num1 = 5;
double num2 = 5.5;
// calling the function
displayNum(num1, num2);
return 0;
}
Vectors in C++ Language
In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library. To use vectors, we need to include the vector header file in our program.
Declaration for Vectors in C++
std::vector<T> vector_name;
Initialization for Vectors in C++
// Vector initialization method 1
// Initializer list
vector<int> vector1 = {1, 2, 3, 4, 5};
// Vector initialization method 2
vector<int> vector3(5, 12);
vector<int> vector2 = {8, 8, 8, 8, 8};
Syntax for Vector Iterators in C++
vector<T>::iterator iteratorName;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* Vectors in C++ language */
// C++ program to illustrate the capacity function in vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> myvector;
for (int i = 1; i <= 5; i++)
myvector.push_back(i);
cout << "Size : " << myvector.size();
cout << "\nCapacity : " << myvector.capacity();
cout << "\nMax_Size : " << myvector.max_size();
// resizes the vector size to 4
myvector.resize(4);
// prints the vector size after resize()
cout << "\nSize : " << myvector.size();
// checks if the vector is empty or not
if (myvector.empty() == false)
cout << "\nVector is not empty";
else
cout << "\nVector is empty";
// Shrinks the vector
myvector.shrink_to_fit();
cout << "\nVector elements are: ";
for (auto it = myvector.begin(); it != myvector.end(); it++)
cout << *it << " ";
return 0;
}
Functional Library greater in C++
Function object class for greater-than inequality comparison. Binary function object class whose call returns whether the its first argument compares greater than the second (as returned by operator >).
The std::greater is a functional object which is used for performing comparisons. It is defined as a Function object class for the greater-than inequality comparison. This can be used for changing the functionality of the given function. This can also be used with various standard algorithms such as sort, priority queue, etc.
Generically, function objects are instances of a class with member function operator() defined. This member function allows the object to be used with the same syntax as a function call.
Syntax for greater in C++
#include <functional>
template <class T> struct greater;
T
Type of the arguments to compare by the functional call. The type shall support the operation (operator>).
Objects of this class can be used on standard algorithms such as sort, merge or lower_bound.
Member types
first_argument_type - T - Type of the first argument in member operator()
second_argument_type - T - Type of the second argument in member operator()
result_type - bool - Type returned by member operator()
Member functions
bool operator() (const T& x, const T& y)
Member function returning whether the first argument compares greater than the second (x>y).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* It is a function object class for greater-than inequality comparison and binary function object class whose call returns whether the its first argument compares greater than the second (as returned by operator >). */
/* Function object class for greater-than inequality comparison by std::greater code example */
#include <functional>
#include <iostream>
#include <queue>
using namespace std;
// Function to print elements of priority_queue
void showpq(priority_queue<int, vector<int>,
greater<int> >
pq)
{
priority_queue<int,
vector<int>,
greater<int> >
g;
g = pq;
// While priority_queue is not empty
while (!g.empty()) {
// Print the top element
cout << g.top() << ' ';
// Pop the top element
g.pop();
}
}
// Driver Code
int main()
{
// priority_queue use to implement
// Max Heap, but using function
// greater <int> () it implements
// Min Heap
priority_queue<int, vector<int>,
greater<int> >
gquiz;
// Inserting Elements
gquiz.push(10);
gquiz.push(30);
gquiz.push(20);
gquiz.push(5);
gquiz.push(1);
// Print elements of priority queue
cout << "The priority queue gquiz is : ";
showpq(gquiz);
return 0;
}
For Loop Statement in C++
In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Syntax of For Loop Statement in C++
for (initialization; condition; update) {
// body of-loop
}
initialization
initializes variables and is executed only once.
condition
if true, the body of for loop is executed, if false, the for loop is terminated.
update
updates the value of initialized variables and again checks the condition.
A new range-based for loop was introduced to work with collections such as arrays and vectors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* For Loop Statement in C++ Language */
// C++ program to find the sum of first n natural numbers
// positive integers such as 1,2,3,...n are known as natural numbers
#include <iostream>
using namespace std;
int main() {
int num, sum;
sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
for (int i = 1; i <= num; ++i) {
sum += i;
}
cout << "Sum = " << sum << endl;
return 0;
}
#include Directive in C++
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Syntax for #include Directive in C++
#include "user-defined_file"
#include <header_file>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* using #include directive in C language */
#include <stdio.h>
int main()
{
/*
* C standard library printf function
* defined in the stdio.h header file
*/
printf("I love you Clementine");
printf("I love you so much");
printf("HappyCodings");
return 0;
}
Namespaces in C++ Language
Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc.
Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name {
// code declarations
}
name::code; // code could be variable or function.
Using Directive
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace.
Discontiguous Namespaces
A namespace can be defined in several parts and so a namespace is made up of the sum of its separately defined parts. The separate parts of a namespace can be spread over multiple files.
So, if one part of the namespace requires a name defined in another file, that name must still be declared. Writing a following namespace definition either defines a new namespace or adds new elements to an existing one:
namespace namespace_name {
// code declarations
}
Nested Namespaces
Namespaces can be nested where you can define one namespace inside another name space as follows:
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* namespaces in C++ language */
// A C++ code to demonstrate that we can define
// methods outside namespace.
#include <iostream>
using namespace std;
// Creating a namespace
namespace ns
{
void display();
class happy
{
public:
void display();
};
}
// Defining methods of namespace
void ns::happy::display()
{
cout << "ns::happy::display()\n";
}
void ns::display()
{
cout << "ns::display()\n";
}
// Driver code
int main()
{
ns::happy obj;
ns::display();
obj.display();
return 0;
}
main() Function in C++
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Syntax for main() Function in C++
void main()
{
............
............
}
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library.
In place of void we can also use int return type of main() function, at that time main() return integer type value.
1) It cannot be used anywhere in the program
a) in particular, it cannot be called recursively
b) its address cannot be taken
2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace).
3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static.
4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;.
5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program).
6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed).
7) (since C++20) The main function cannot be a coroutine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* simple code example by main() function in C++ */
#include <iostream>
using namespace std;
int main() {
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
return 0;
}
Vector Library begin() Function in C++
Return iterator to beginning. Returns an iterator pointing to the first element in the vector. Notice that, unlike member vector::front, which returns a reference to the first element, this function returns a random access iterator pointing to it.
If the container is empty, the returned iterator value shall not be dereferenced.
The C++ function std::vector::begin() returns a random access iterator pointing to the first element of the vector.
Syntax for Vector begin() Function in C++
#include <vector>
iterator begin() noexcept;
const_iterator begin() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* returns a random access iterator pointing to the first element of the vector by std::vector::begin() function code example. */
// CPP program to illustrate implementation of begin() function
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// declaration of vector container
vector<string> myvector{ "This", "is",
"HappyCodings" };
// using begin() to print vector
for (auto it = myvector.begin();
it != myvector.end(); ++it)
cout << ' ' << *it;
return 0;
}
Inline Functions in C++
Inline function is one of the important feature of C++. So, let's first understand why inline functions are used and what is the purpose of inline function?
When the program executes the function call instruction the CPU stores the memory address of the instruction following the function call, copies the arguments of the function on the stack and finally transfers control to the specified function. The CPU then executes the function code, stores the function return value in a predefined memory location/register and returns control to the calling function. This can become overhead if the execution time of function is less than the switching time from the caller function to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run. However, for small, commonly-used functions, the time needed to make the function call is often a lot more than the time needed to actually execute the function's code. This overhead occurs for small functions because execution time of small function is less than the switching time.
C++ provides an inline functions to reduce the function call overhead. Inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler at compile time. Inline function may increase efficiency if it is small.
Syntax for Defining the Function Inline
inline return-type function-name(parameters)
{
// function code
}
Inline Functions Provide Following Advantages
• Function call overhead doesn't occur.
• It also saves the overhead of push/pop variables on the stack when function is called.
• It also saves overhead of a return call from a function.
• When you inline a function, you may enable compiler to perform context specific optimization on the body of function. Such optimizations are not possible for normal function calls. Other optimizations can be obtained by considering the flows of calling context and the called context.
• Inline function may be useful (if it is small) for embedded systems because inline can yield less code than the function call preamble and return.
Inline Function Disadvantages
• The added variables from the inlined function consumes additional registers, After in-lining function if variables number which are going to use register increases than they may create overhead on register variable resource utilization. This means that when inline function body is substituted at the point of function call, total number of variables used by the function also gets inserted. So the number of register going to be used for the variables will also get increased. So if after function inlining variable numbers increase drastically then it would surely cause an overhead on register utilization.
• If you use too many inline functions then the size of the binary executable file will be large, because of the duplication of same code.
• Too much inlining can also reduce your instruction cache hit rate, thus reducing the speed of instruction fetch from that of cache memory to that of primary memory.
• Inline function may increase compile time overhead if someone changes the code inside the inline function then all the calling location has to be recompiled because compiler would require to replace all the code once again to reflect the changes, otherwise it will continue with old functionality.
• Inline functions may not be useful for many embedded systems. Because in embedded systems code size is more important than speed.
• Inline functions might cause thrashing because inlining might increase size of the binary executable file. Thrashing in memory causes performance of computer to degrade.
Inline Function And Classes
It is also possible to define the inline function inside the class. In fact, all the functions defined inside the class are implicitly inline. Thus, all the restrictions of inline functions are also applied here. If you need to explicitly declare inline function in the class then just declare the function inside the class and define it outside the class using inline keyword.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/* If make a function as inline, then the compiler replaces the function calling location with the definition of the inline function at compile time. Any changes made to an inline function will require the inline function to be recompiled again because the compiler would need to replace all the code with a new code; otherwise, it will execute the old functionality. */
#include <iostream>
using namespace std;
class operation
{
int a,b,add,sub,mul;
float div;
public:
void get();
void sum();
void difference();
void product();
void division();
};
inline void operation :: get()
{
cout << "Enter first value:";
cin >> a;
cout << "Enter second value:";
cin >> b;
}
inline void operation :: sum()
{
add = a+b;
cout << "Addition of two numbers: " << a+b << "\n";
}
inline void operation :: difference()
{
sub = a-b;
cout << "Difference of two numbers: " << a-b << "\n";
}
inline void operation :: product()
{
mul = a*b;
cout << "Product of two numbers: " << a*b << "\n";
}
inline void operation ::division()
{
div=a/b;
cout<<"Division of two numbers: "<<a/b<<"\n" ;
}
int main()
{
cout << "Program using inline function\n";
operation s;
s.get();
s.sum();
s.difference();
s.product();
s.division();
return 0;
}
Vector Library Operator Index [] in C++
Access element. Returns a reference to the element at position n in the vector container.
A similar member function, vector::at, has the same behavior as this operator function, except that vector::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception.
Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.
Syntax for Vector Operator Index [] in C++
#include <vector>
reference operator[] (size_type n);
const_reference operator[] (size_type n) const;
n
Position of an element in the container. Notice that the first element has a position of 0 (not 1). Member type size_type is an unsigned integral type.
Function returns the element at the specified position in the vector.
If the vector object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference.
Member types reference and const_reference are the reference types to the elements of the container (see vector member types).
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). The reference returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
If the container size is greater than n, the function never throws exceptions (no-throw guarantee). Otherwise, the behavior is undefined.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* Returns a reference to the element at specified location pos. No bounds checking is performed. Unlike std::map::operator[], this operator never inserts a new element into the container. Accessing a nonexistent element through this operator is undefined behavior. */
/* Access element from a vector by vector::operator[] code example */
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector (10); // 10 zero-initialized elements
std::vector<int>::size_type sz = myvector.size();
// assign some values:
for (unsigned i=0; i<sz; i++) myvector[i]=i;
// reverse vector using operator[]:
for (unsigned i=0; i<sz/2; i++)
{
int temp;
temp = myvector[sz-1-i];
myvector[sz-1-i]=myvector[i];
myvector[i]=temp;
}
std::cout << "myvector contains:";
for (unsigned i=0; i<sz; i++)
std::cout << ' ' << myvector[i];
std::cout << '\n';
return 0;
}
Algorithm Library sort_heap() Function in C++
Sort elements of heap. Sorts the elements in the heap range [first,last) into ascending order. C++ algorithm::sort_heap function is used to sort elements in the heap range [first,last) into ascending order.
The elements are compared using operator< for the first version, and comp for the second, which shall be the same as used to construct the heap.
The range loses its properties as a heap.
Syntax for sort_heap() Function in C++
#include <algorithm>
//default (1)
template <class RandomAccessIterator>
void sort_heap (RandomAccessIterator first, RandomAccessIterator last);
//custom (2)
template <class RandomAccessIterator, class Compare>
void sort_heap (RandomAccessIterator first, RandomAccessIterator last,
Compare comp);
first, last
Random-access iterators to the initial and final positions of the heap range to be sorted. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
comp
Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines. Unless [first,last) is a one-element heap, this argument shall be the same as used to construct the heap.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
This function does not return any value.
Complexity
Up to linearithmic in the distance between first and last: Performs at most N*log(N) (where N is this distance) comparisons of elements, and up to that many element swaps (or moves).
Data races
The objects in the range [first,last) are modified.
Exceptions
Throws if any of the element comparisons, the element swaps (or moves) or the operations on iterators throws. Note that invalid arguments cause undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* C++ Algorithm sort_heap() function is used to converts a heap [first, last) into a sorted range in ascending order. Elements are compared using operator< for the first version or using the given binary comparison function comp for the second version. */
/* Sort elements of heap by sort_heap() function code example */
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main (){
vector<int> vec{10, 5, 55, 22, 27, -10};
vector<int>::iterator it;
cout<<"vec contains:";
for(it = vec.begin(); it != vec.end(); ++it)
cout<<" "<<*it;
//make the vector max heap
make_heap(vec.begin(), vec.end());
cout<<"\nAfter make_heap call, vec contains:";
for(it = vec.begin(); it != vec.end(); ++it)
cout<<" "<<*it;
//sort the max heap
sort_heap(vec.begin(), vec.end());
cout<<"\nAfter sort_heap call, vec contains:";
for(it = vec.begin(); it != vec.end(); ++it)
cout<<" "<<*it;
return 0;
}
Vector Library push_back() Function in C++
Add element at the end. Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.
This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.
push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1.
Syntax for Vector push_back() Function in C++
#include <vector>
void push_back (const value_type& val);
void push_back (value_type&& val);
val
Value to be copied (or moved) to the new element. Member type value_type is the type of the elements in the container, defined in vector as an alias of its first template parameter (T).
This function does not return any value.
If a reallocation happens, the storage is allocated using the container's allocator, which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).
Complexity
Constant (amortized time, reallocation may happen). If a reallocation happens, the reallocation is itself up to linear in the entire size.
Iterator validity
If a reallocation happens, all iterators, pointers and references related to the container are invalidated.
Otherwise, only the end iterator is invalidated, and all iterators, pointers and references to elements are guaranteed to keep referring to the same elements they were referring to before the call.
Data races
The container is modified. If a reallocation happens, all contained elements are modified.
Otherwise, no existing element is accessed, and concurrently accessing or modifying them is safe.
Exception safety
If no reallocations happen, there are no changes in the container in case of exception (strong guarantee).
If a reallocation happens, the strong guarantee is also given if the type of the elements is either copyable or no-throw moveable.
Otherwise, the container is guaranteed to end in a valid state (basic guarantee).
If allocator_traits::construct is not supported with val as argument, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* vector::push_back() is a library function of "vector" header, it is used to insert/add an element at the end of the vector, it accepts an element of the same type and adds the given element at the end of the vector and increases the size of the vector. */
//C++ STL program code example to demonstrate example of vector::push_back() function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
//vector declaration
vector<int> v1;
//inserting elements and printing size
cout << "size of v1: " << v1.size() << endl;
v1.push_back(10);
cout << "size of v1: " << v1.size() << endl;
v1.push_back(20);
v1.push_back(30);
v1.push_back(40);
v1.push_back(50);
cout << "size of v1: " << v1.size() << endl;
//printing all elements
cout << "elements of vector v1..." << endl;
for (int x : v1)
cout << x << " ";
cout << endl;
return 0;
}
Function Templates in C++
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.
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.
Syntax for Function Templates in C++
template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}
Ttype
a placeholder name
class
specify a generic type
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.
• 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.
• The type of the data that the function will operate on depends on the type of the data passed as a parameter.
• For example, Quick sorting algorithm is implemented using a generic function, it can be implemented to an array of integers or array of floats.
• A Generic function is created by using the keyword template. The template defines what function will do.
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.
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of function.
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* function templates in C++ language */
/* adding two numbers using function templates */
#include <iostream>
using namespace std;
template <typename T>
T add(T num1, T num2) {
return (num1 + num2);
}
int main() {
int result1;
double result2;
// calling with int parameters
result1 = add<int>(2, 3);
cout << "2 + 3 = " << result1 << endl;
// calling with double parameters
result2 = add<double>(2.2, 3.3);
cout << "2.2 + 3.3 = " << result2 << endl;
return 0;
}
Iterators in C++ Language
Iterators are just like pointers used to access the container elements. Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent.
Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container. They allow you to iterate over the container, access and assign the values, and run different operators over them, to get the desired result.
Syntax for Iterators in C++
<ContainerType> :: iterator;
<ContainerType> :: const_iterator;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* Iterators in C++ language */
// C++ code to demonstrate the working of next() and prev()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
// Declaring iterators to a vector
vector<int>::iterator ptr = ar.begin();
vector<int>::iterator ftr = ar.end();
// Using next() to return new iterator
// points to 4
auto it = next(ptr, 3);
// Using prev() to return new iterator
// points to 3
auto it1 = prev(ftr, 3);
// Displaying iterator position
cout << "The position of new iterator using next() is : ";
cout << *it << " ";
cout << endl;
// Displaying iterator position
cout << "The position of new iterator using prev() is : ";
cout << *it1 << " ";
cout << endl;
return 0;
}
Class Templates in C++
Templates are powerful features of C++ which allows us to write generic programs. Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration.
Declaration for Class Template in C++
template <class T>
class className {
private:
T var;
... .. ...
public:
T functionName(T arg);
... .. ...
};
T
template argument
var
a member variable
T is the template argument which is a placeholder for the data type used, and class is a keyword.
Inside the class body, a member variable var and a member function functionName() are both of type T.
Creating a class template object:
Once we've declared and defined a class template, we can create its objects in other classes or functions (such as the main() function) with the following syntax:
className<dataType> classObject;
template <class T>
class ClassName {
... .. ...
// Function prototype
returnType functionName();
};
// Function definition
template <class T>
returnType ClassName<T>::functionName() {
// code
}
template <class T, class U, class V = int>
class ClassName {
private:
T member1;
U member2;
V member3;
... .. ...
public:
... .. ...
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. A template is a blueprint or formula for creating a generic class or a function. */
#include <iostream>
using namespace std;
template <typename T>
class Array {
private:
T *ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T>
Array<T>::Array(T arr[], int s) {
ptr = new T[s];
size = s;
for(int i = 0; i < size; i++)
ptr[i] = arr[i];
}
template <typename T>
void Array<T>::print() {
for (int i = 0; i < size; i++)
cout<<" "<<*(ptr + i);
cout<<endl;
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
Array<int> a(arr, 5);
a.print();
return 0;
}
Algorithm finds the median of 2 sorted arrays using binary search approach. Takes the input of 'n' Data Elements of both the arrays. Using decrease, conquer method find the combined