0% found this document useful (0 votes)
10 views

OOPS6

Object Oriented Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

OOPS6

Object Oriented Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT VI

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

● Generics is the idea to allow type (Integer, String, … etc and


user-defined types) to be a parameter to methods, classes and
interfaces. For example, classes like an array, map, etc,
● The method of Generic Programming is implemented to
increase the efficiency of the code.
● Generic Programming enables the programmer to write a
general algorithm which will work with all data types.
● It eliminates the need to create different algorithms if the data
type is an integer, string or a character.
Advantages of Generic Programming
•The advantages of Generic Programming are

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.

■ Function templates allow the logic to be


written once and used for all data types –
generic function.
Templates
● Template is a simple and yet very powerful tool in C++.
● The simple idea is to pass data type as a parameter so that
we don’t need to write the same code for different data
types.
● For example, you need to sort() for different data
types. Rather than writing and maintaining multiple
codes, we can write one sort() and pass the datatype as a
parameter.
● C++ adds two new keywords to support templates:
‘template’ and ‘type name’. The second keyword can
always be replaced by the keyword ‘class’.
How Do Templates Work?
● Templates are expanded at compile time. This is like macros.
● The difference is, that the compiler does type-checking
before template expansion.
● The idea is simple, source code contains only function/class,
but compiled code may contain multiple copies of the same
function/class.’.

template < class Ttype> ret_type func_name(parameter_list)


{
// body of function.
}
■ Write a function to return maximum of 3
integers.
■ Write a function to return maximum of 3
floating point numbers.
Function maximum() : returns maximum of 3 numbers

int maximum(int a, int b, int c)


{ float maximum(float a, float b,
int max = a; float c)
if (b > max) max = b; {
if (c > max) max = c; float max = a;
return max; if (b > max) max = b;
} if (c > max) max = c;
return max;
}

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?

Templates are expanded at compile time.


This is like macros.
The difference is, compiler does type checking before template
expansion.
The idea is simple, source code contains only function/class, but
compiled code may contain multiple copies of same
function/class.
Class template

•In C++, class templates are a powerful feature that


allows you to create generic classes.
• With a class template, you can design a class to
work with any data type without specifying the type
upfront.
• This avoids code duplication and makes the code
more flexible.
Class template
■ To make a class into a template, prefix the class definition with the syntax:
template< class T >
Here T is just a type parameter. Like a function parameter, it is a place

holder.
When the class is instantiated, T is replaced by a real type.

■ To access a member function, use the following syntax:


className< T >:: memberName.

SimpleList < T > :: SimpleList()


■ Using the class template:


ClassName<real type> variable;

SimpleList < int > list1;


16
Basic Syntax of Class Template

• template <typename T> // or 'class T' class


ClassName
• { public:
• T data; // T is a placeholder for the data type
• ClassName(T value) : data(value) {} // Constructor
• void display()
• { std::cout << "Data: " << data << std::endl; }
• };
Class template with multiple parameters
template <typename T> int main()
class MyClass { // Creating an object of MyClass
{private: with int type
T data; MyClass intObj(42);
public: //Constructor to initialize data intObj.display(); // Output: Data:
MyClass(T value) : data(value) 42
{ // Creating an object of MyClass
} with string type
// Function to display the data MyClass stringObj("Hello,
void display() Templates!");
{ cout << "Data: " << data << endl;
stringObj.display();
}
// Output: Data: Hello, Templates!
};
return 0;}
Class template with multiple parameters
● While creating templates, it is possible to specify more than one type.
We can use more than one generic data type in a class template.
● They are declared as a comma-separated list within the template as
below:
● Syntax:

template<class T1, class T2, ...> class classname


{
...
...
};
Class template with multiple parameters
template<class T1, class T2> class int main(){
Test { // instantiation with float and int type
T1 a; T2 b; Test <float, int> test1 (1.23, 123);
public:
Test(T1 x, T2 y){
a = x; // instantiation with float and char type
b = y; Test <int, char> test2 (100, 'W');
}
void show() { test1.show();
cout << a << " and " << b << endl;
test2.show();
}
};
return 0;
}
Output:
1.23 and 123
100 and
W
demonstrates using two different data types in the same template class
• template <typename T1, typename T2>
• class Pair {
• private: T1 first; T2 second;
• public:
• Pair(T1 f, T2 s) : first(f), second(s) {}
• void display()
• { cout << "First: " << first << ", Second: " << second << endl; }};
• int main()
• { Pair<int, string> p(1, "One");
• p.display(); // Output: First: 1, Second: One
• return 0;}
Key features of Class templates
• Class templates allow you to write generic classes
that work with different types.
• You can use multiple type parameters to increase
flexibility.
• Templates are especially useful in data structures,
algorithms, and libraries like the Standard
Template Library (STL).
STL?
The Standard Template Library (STL) is a
powerful library in C++ that provides a
collection of generic classes and functions to
work with data structures and algorithms.
The STL components are designed in a generic
way, allowing them to work with any data type.
Key Features:
• Generic Programming: Allows reuse of code for
different data types.
• Efficiency: Well-tested algorithms and data structures
ensure optimized performance.
• Consistency: Provides uniform interfaces and
behavior for different containers.
• Extensibility: Users can define custom data types or
algorithms compatible with STL.
Components of STL

• The STL is divided into four key components:


• 1. Containers
• 2. Algorithms
• 3. Iterators
• 4. Functors (Function Objects)
1. Containers
• Containers are objects that store collections of data. The
STL provides various types of containers for different use
cases. Containers are broadly classified into:
• Sequence Containers: Maintain elements in a sequence
(linear order).
Examples:
–vector: Dynamic array
–list: Doubly linked list
–deque: Double-ended queue
• Associative Containers: Store elements in sorted order
based on keys.
Examples:
–set: Collection of unique elements
–map: Key-value pairs with unique keys
• Unordered Containers: Provide faster access by using
hashing (unordered but fast lookup).
Examples:
–unordered_set: Unordered collection of unique elements
–unordered_map: Key-value pairs with unordered keys
• 2. Algorithms
• STL provides a wide range of generic algorithms to
operate on containers, such as searching, sorting, or
modifying data.
Examples of algorithms:
• sort(): Sorts elements in ascending or descending order.
• find(): Searches for a specific element.
• binary_search(): Performs a binary search on a sorted
container.
• for_each(): Applies a function to each element in a
container.
• 3. Iterators
• Iterators act as pointers to traverse elements in containers.
They bridge the gap between containers and algorithms by
providing a uniform way to access elements.
Types of Iterators:
• Input Iterator: Read values from a container.
• Output Iterator: Write values to a container.
• Forward Iterator: Traverse in one direction.
• Bidirectional Iterator: Traverse in both directions.
• Random Access Iterator: Directly access any element (like an
array index).
4. Functors (Function Objects)

• A functor is an object that behaves like a function.


STL allows functors to be passed to algorithms for
greater flexibility.
Example:
• greater<int>() can be passed to the sort() algorithm to
sort elements in descending order.
Benefits of Using STL
• Code Reusability: Templates and generic programming
eliminate the need for duplicating code for different data
types.
• Performance: STL algorithms and containers are highly
optimized for efficiency.
• Consistency: A uniform interface makes it easy to switch
between different containers and algorithms.
• Reduced Development Time: Ready-made data structures
and algorithms save developers from reinventing the wheel.
Disadvantages of the C++ Standard Template Library (STL):

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; }

You might also like