W12-Templates and STL
W12-Templates and STL
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;
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;
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;
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
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
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
19
STL vector
Defining a new vector
• Syntax: vector<of what>
• 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);
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;
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 << " ";
}
24
STL vector + algorithm
Sort a vector of integers
#include <iostream>
#include <vector>
using namespace std;
int main() {
int input;
vector<int> ivec;
• 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;
return 0;
} 31
STL list + algorithm
Example 2 of list #include <iostream>
#include <list>
#include <algorithm> // for std::for_each
int main() {
// Create a list of integers
list<int> myList;
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;
Thank You!