0% found this document useful (0 votes)
16 views39 pages

W12-Templates and STL

The document covers C++ templates and the Standard Template Library (STL), focusing on class templates and their usage. It explains the components of STL, including containers, iterators, and algorithms, with examples of STL vector and list. Additionally, it highlights the benefits of using templates for code reusability and the efficiency of STL data structures.

Uploaded by

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

W12-Templates and STL

The document covers C++ templates and the Standard Template Library (STL), focusing on class templates and their usage. It explains the components of STL, including containers, iterators, and algorithms, with examples of STL vector and list. Additionally, it highlights the benefits of using templates for code reusability and the efficiency of STL data structures.

Uploaded by

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

SC1008 C and C++ Programming

Assistant Professor WANG Yong


[email protected]
CCDS, Nanyang Technological University
Week 12
Templates and Standard Template Library
Outline
• Templates
- Class templates

• Standard Template Library (STL)


- Container, iterator, algorithm
- STL vector
- STL list
- STL map

3
Templates
• A 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
• Two types of templates in C++:
- Function Templates
- Class Templates

4
How Do Templates Work?
• Templates are expanded at compiler time, which is like macros
• But different from macros, the compiler does type-checking
before expanding templates
• The source code contains only function/class, but compiled
code may contain multiple copies of the same
function/class
The keyword “typename” can also be replaced by “class”

https://www.geeksforgeeks.org/templates-cpp/ 5
#include <iostream>
using namespace std;

Class Templates template <typename T>


class Array {
private:

• Like function templates, class T* ptr;


int size;

templates are useful when a


public:
Array(T arr[], int s);
~Array(); // Destructor to free memory
class defines something that is void print();
};

independent of the data type. template <typename T>


Array<T>::Array(T arr[], int s) {
ptr = new T[s];
size = s;
• The example code implements for (int i = 0; i < size; i++)
ptr[i] = arr[i];
a template Array class }

template <typename T>


Array<T>::~Array() { delete[] ptr; }

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;
https://www.geeksforgeeks.org/templates-cpp/ } 6
#include <iostream>
using namespace std;

Class Templates template <typename T>


class Array {
private:

• Like function templates, class T* ptr;


int size;

templates are useful when a


public:
Array(T arr[], int s);
~Array(); // Destructor to free memory
class defines something that is void print();
};

independent of the data type. template <typename T>


Array<T>::Array(T arr[], int s) {
ptr = new T[s];
size = s;
• The example code implements for (int i = 0; i < size; i++)
ptr[i] = arr[i];
a template Array class }
Remember to free allocated memory
template <typename T>
Array<T>::~Array() { delete[] ptr; }

1. Key points of defining member functions template <typename T>


void Array<T>::print() {
for (int i = 0; i < size; i++)
cout << " " << *(ptr + i);
cout << endl;
}

int main() {
2. Key point of using class templates int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a(arr, 5);
a.print();
return 0;
https://www.geeksforgeeks.org/templates-cpp/ } 7
#include <iostream>
using namespace std;

Class Templates template <typename T>


class Array {
private:

• Like function templates, class T* ptr;


int size;

templates are useful when a


public:
Array(T arr[], int s);
~Array(); // Destructor to free memory
class defines something that is void print();
};

independent of the data type. template <typename T>


Array<T>::Array(T arr[], int s) {
ptr = new T[s];
size = s;
• The example code implements for (int i = 0; i < size; i++)
ptr[i] = arr[i];
a template Array class }

template <typename T>


Array<T>::~Array() { delete[] ptr; }

template <typename T>


void Array<T>::print() {
for (int i = 0; i < size; i++)
cout << " " << *(ptr + i);
cout << endl;
}

Program output: int main() {


int arr[5] = { 1, 2, 3, 4, 5 };
12345 Array<int> a(arr, 5);
a.print();
return 0;
https://www.geeksforgeeks.org/templates-cpp/ } 8
Class Templates with Multiple Parameters
• We can pass more than one data type as arguments to class
templates #include <iostream>
using namespace std;
• Syntax
// Class template with two parameters
template <class T1, class T2>
class Test {
T1 a;
T2 b;
public:
Test(T1 x, T2 y) {
a = x;
b = y;
}
void show() {
cout << a << " and " << b << endl;
}
};

int main() {
Test<float, int> test1(1.23, 123);
Test<int, char> test2(100, 'W’);
test1.show();
test2.show();
return 0;
}
https://www.geeksforgeeks.org/templates-cpp/ 9
Class Templates with Multiple Parameters
• We can pass more than one data type as arguments to class
templates #include <iostream>
using namespace std;
• Syntax
// Class template with two parameters
template <class T1, class T2>
class Test {
T1 a;
T2 b;
public:
Test(T1 x, T2 y) {
a = x;
b = y;
}
void show() {
cout << a << " and " << b << endl;
}
};
This is how we define and use a class
int main() {
template with multiple data types Test<float, int> test1(1.23, 123);
Test<int, char> test2(100, 'W’);
test1.show();
test2.show();
return 0;
}
https://www.geeksforgeeks.org/templates-cpp/ 10
L15: C++ STL CSE333, Fall 2022

C++’s Standard Library


C++’s Standard Library consists of four major pieces:
1) The entire C standard library
2) C++’s input/output stream library
• std::cin, std::cout, stringstreams, fstreams, etc.

3) C++’s Standard Template Library (STL) ☜


• Containers, iterators, algorithms (sort, find, etc.)

4) C++’s miscellaneous library


• Strings, exceptions, memory allocation, localization
C++ Standard Template Library (STL)
• STL: a library containing many templates for frequently
used data structures and algorithms

• STL had three basic components:


– Containers
Generic class templates for storing collection of data
– Algorithms
Generic function templates for operating on containers
– Iterators
Generalized ‘smart’ pointers that facilitate use of containers.
They provide an interface that is needed for STL algorithms to
operate on STL containers

12
Containers
• Containers: Data structures that hold anything (other
objects)
• Two types of container classes in STL:
– Sequence containers: organize and access data sequentially, as in
an array. These include vector, dequeue, and list
– Associative containers: use keys to allow data elements to be
quickly accessed. These include set, multiset, map, and
multimap

13
Containers
• This class will mainly focus on vector, list and map

Note: The above tables are not an exhaustive list of all the containers in STL. More can be
found here: https://cplusplus.com/reference/stl/
14
Iterators

❖ Each container class has an associated iterator class (e.g.


vector<int>::iterator) used to iterate through
elements of the container
end is not
▪ https://cplusplus.com/reference/iterator/iterator/?kw=iterator included!
▪ Iterator range is from begin up to end i.e., [begin , end)
• end is the one past the last container element!
▪ Some container iterators support more operations than others
• All can be incremented (++), copied, copy-constructed
• Some can be dereferenced on right-hand side (e.g. x = *it;)
• Some can be dereferenced on left-hand side (e.g. *it = x;)
• Some can be decremented (--)
• Some support random access ([], +, -, +=, -=, <, > operators)

15
Algorithms
• STL contains algorithms that are implemented as function
templates to perform common tasks on containers
• Requires algorithm header file
• The common tasks include searching, sorting, comparing,
and editing, etc. Thus, algorithm includes
binary_search count
for_each find
find_if max_element
min_element random_shuffle
sort and others

16
Algorithms

17
Algorithms

18
STL vector

❖ A generic, dynamically resizable array


▪ http://www.cplusplus.com/reference/stl/vector/vector/
▪ Elements are stored in contiguous memory locations
• Elements can be accessed using pointer arithmetic if you’d like
• Random access is O(1) time
▪ Adding/removing from the end is cheap (amortized
constant time)
▪ Inserting/deleting from the middle or start is expensive
(linear time)

You are recommended to use STL vector!

19
STL vector
Defining a new vector
• Syntax: vector<of what>

• Remember to include the source file


#include <vector>

• Examples:
vector<int> - vector of integers.
vector<string> - vector of strings.
vector<int *> - vector of pointers to integers.
vector<Shape> - vector of Shape objects. Shape is a
user defined class.

20
STL vector
Using vector
• There are two ways to use the vector type:
- Array style
- STL style (the recommended one!)

21
STL vector
• Array style: we mimic the use of the built-in array
#include <iostream>
#include <vector>
using namespace std;

int main() {
const int N = 5;
vector<int> ivec(N);

// Input values into vector


cout << "Enter 5 integers: ";
for (int i = 0; i < N; ++i)
cin >> ivec[i];

// Display copied array values


cout << "Array contents: ";
for (int j = 0; j < N; ++j)
cout << ivec[j] << " ";
cout << endl;

return 0;
}

22
STL vector
• STL style: we can use the iterator and algorithm provided in
STL
#include <iostream>
#include <vector>
using namespace std;

int main() {
int input;
vector<int> ivec;

// Input values into vector using iterator


cout << "Enter 5 integers: "; While-loop stops until an invalid input (e.g.,
while (cin >> input )
letters) is given, which results in an input failure.
ivec.push_back(input);

// Display values using iterator


cout << "Array contents: ";
vector<int>::iterator it;
for ( it = ivec.begin(); it != ivec.end(); ++it ) {
cout << *it << " ";
}

cout << endl;


return 0;
}

23
STL vector
• STL style: we can use the iterator and algorithm provided in
STL
#include <iostream>
#include <vector>
using namespace std;

int main() {
int input; push_back(): Insert a value to the back of the
vector<int> ivec; vector
// Input values into vector using iterator
cout << "Enter 5 integers: ";
while (cin >> input ) An iterator for vector of integer
ivec.push_back(input);
iterator range
// Display values using iterator
cout << "Array contents: ";
vector<int>::iterator it;
for ( it = ivec.begin(); it != ivec.end(); ++it ) {
cout << *it << " ";
}

cout << endl;


return 0;
}

24
STL vector + algorithm
Sort a vector of integers
#include <iostream>
#include <vector>
using namespace std;

int main() {
int input;
vector<int> ivec;

// Input values into vector using iterator


cout << "Enter 5 integers: ";
while (cin >> input )
ivec.push_back(input); Sort the whole vector of integers.
// sorting
sort(ivec.begin(), ivec.end());

// Display values using iterator


cout << "Array contents: ";
vector<int>::iterator it;
for ( it = ivec.begin(); it != ivec.end(); ++it ) {
cout << *it << " ";
}

cout << endl;


return 0;
} 25
STL vector + algorithm
sort()

• Formal Definition:
void sort(Iterator begin, Iterator end);

• Example:
vector<int> ivec;
// Fill ivec with integers …
sort(ivec.begin(), ivec.end())

26
STL vector – Member Functions
• More member functions can be found in the official documents
https://cplusplus.com/reference/vector/vector/?kw=vector

27
STL list
❖ A generic doubly-linked list
▪ http://www.cplusplus.com/reference/stl/list/
▪ Elements are not stored in contiguous memory locations
• Does not support random access (e.g. cannot do list[5])
▪ Some operations are much more efficient than vectors
• lists is much quicker than vectors to insert or add elements
to their front or their back, since lists do not need to shift the
other elements and have pointers to the first and last element (no
traversal required)
• Can iterate forward or backwards
▪ Has a built-in sort member function
• Doesn’t copy! Manipulates list structure instead of element
values
28
STL list – Member Functions

29
STL list – Member Functions

30
STL list
Example 1 of list
// This program demonstrates the STL list container.
#include <iostream>
#include <list> // Include the list header.
using namespace std;

int main()
{
// Define a list object.
list<int> myList;

// Define an iterator for the list.


Program output: list<int>::iterator iter;

0 10 20 30 40 50 60 70 80 90 // Add values to the list.


90 80 70 60 50 40 30 20 10 0 for (int x = 0; x < 100; x += 10)
myList.push_back(x);

// Display the values.


for (iter = myList.begin(); iter != myList.end(); iter++)
cout << *iter << " ";
cout << endl;

// Now reverse the order of the elements.


myList.reverse();

// Display the values again.


for (iter = myList.begin(); iter != myList.end(); iter++)
cout << *iter << " ";
cout << endl;

return 0;
} 31
STL list + algorithm
Example 2 of list #include <iostream>
#include <list>
#include <algorithm> // for std::for_each

using namespace std;

// Function to print an element


void printElement(int x) {
cout << x << " ";
}

int main() {
// Create a list of integers
list<int> myList;

// Add values to the list.


for (int x = 0; x < 100; x += 10)
myList.push_back(x);

// Use for_each to apply printElement function to each element


cout << "List elements: ";
for_each(myList.begin(), myList.end(), printElement);
cout << endl;

return 0;
}

Program output:
List elements: 0 10 20 30 40 50 60 70 80 90
32
STL list + algorithm

33
STL map
❖ One of C++’s associative containers: a key/value table,
implemented as a search tree
▪ http://www.cplusplus.com/reference/stl/map/
▪ General form: map<key_type, value_type> name;
▪ Keys must be unique
• multimap allows duplicate keys
▪ Efficient lookup (O(log n)) and insertion (O(log n))
• Access value via name[key]
▪ Elements are type pair<key_type, value_type> and are
stored in sorted order (key is field first, value is field second)
• Key type must support less-than operator (<)

34
STL map
• std:pair<key_type, value_type>
- This class couples together a pair of values, which may be
of different types

https://cplusplus.com/reference/utility/pair/?kw=pair 35
STL map – Member Functions

https://cplusplus.com/reference/map/map/?kw=map

36
#include <iostream>

STL map
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> studentGrades;

// Insert elements into the map


studentGrades["Alice"] = 90;
studentGrades["Bob"] = 85;
studentGrades["Charlie"] = 78;
studentGrades["David"] = 92;

// Display all students and their grades


cout << "Student Grades:\n";
map<string, int>::iterator it;
for (it = studentGrades.begin(); it != studentGrades.end();++it) {
cout << it->first << " -> " << it->second << endl;
Program output: }
Student Grades:
Alice -> 90 // Searching for a student
string name = "Charlie";
Bob -> 85 map<string, int>::iterator search = studentGrades.find(name);
Charlie -> 78 if (search != studentGrades.end()) {
David -> 92 cout << "\n" << name << "'s Grade: " << search->second << endl;
} else {
Charlie's Grade: 78 cout << "\nStudent not found!" << endl;
}

Updated Student Grades: // Removing a student


Alice -> 90 studentGrades.erase("Bob");
Charlie -> 78
David -> 92 // Displaying updated map
cout << "\nUpdated Student Grades:\n";
for (it = studentGrades.begin(); it != studentGrades.end(); ++it) {
cout << it->first << " -> " << it->second << endl;
}
return 0;
}
37
References:
[1] Tony Gaddis. Starting out with C++ from control structures through objects, 8th
edition. Chapter 16.3-16.5, Chapter 17.5.
[2] Prata, Stephen. C++ primer plus. Sams Publishing, 2002, 5th edition. Chapters 16.
[3] https://cplusplus.com/
38
Questions?

Thank You!

You might also like