OOPS6
OOPS6
Templates
Introduction,
Function templates,
Class template with multiple parameters.
Introduction to STL: Introduction of STL
components, Sequential container,
Algorithms,
Iterators.
Case Study: Write a program in c++ to create vector
template using STL container.
Generic Programming
1.Code Reusability
2.Avoid Function Overloading
3.Once written it can be used for multiple times and
cases.
•Generics can be implemented in C++ using
Templates.
• int big(int x,int y)
• { if(x > y)
• return x;
• else
• return y; }
• int main()
• { cout << big(4,5);
• cout << big(4.8,9.5);
• return 0;}
• template <typename T>
• T big(T x,T y)
• { if(x > y)
• return x;
• else return y;
• }
• int main(){
• cout << big(4,5);
• cout << big(4.8,9.5);
• return 0;}
GENERIC FUNCTIONS
■ The logic is exactly the same, but the data
type is different.
11
Function Templates
● We write a generic function that can be used for different data types.
Examples of function templates are sort(), max(), min(), printArray().
How templates work?
holder.
When the class is instantiated, T is replaced by a real type.
■
16
Basic Syntax of Class Template
1.Learning curve: The STL can be difficult to learn, especially for beginners, due
to its complex syntax and use of advanced features like iterators and function
objects.
2.Lack of control: When using the STL, you have to rely on the implementation
provided by the library, which can limit your control over certain aspects of
your code.
3.Performance: In some cases, using the STL can result in slower execution times
compared to custom code, especially when dealing with small amounts of data.
#include <iostream> #include <vector> #include <algorithm> // for sort()
• using namespace std;
• int main()
• {
• vector<int> numbers = {4, 2, 8, 1, 5};
• sort(numbers.begin(), numbers.end()); // Sort the in ascending order using sort()
• cout << "Sorted numbers: "; // Display the sorted elements
• for (int num : numbers) {
• cout << num << " ";
• }
• cout << endl;
• return 0; }