Part 6 - Templates, Containers, Vectors, Iterators, STL Algorithms Flashcards
What does
template <class></class>
above a method indicate?
T is a type parameter that can be instantiated with any type
So at compile time a version of the method will be generated for each type that uses it
Write a template version of the swap function
template <class></class>
void swap(T& a, T& b) {
T tmp = a;
a = b;
b = tmp;
}
Write a method that prints a pair where each member of the pair can be of a different type
template <class></class>
void printPair(const S& s, const T& t) {
cout << s << “, “ << t << endl;
}
What is a template class?
A class where one of the members can be of any type
Write the header for a class Pair that has two members of any type, a constructor and two methods getFirst and getSecond
template <class></class>
class Pair {
private:
S first;
T second;
public:
Pair(S s, T t) : first(s), second(t){};
S getFirst() const { return first; }
T getSecond() const { return second; }
};
Why must a template class be written as one file?
Writing a separate file wont work because the type names S or T or whatever wont be in scope in the .cpp file. So has to be written in the header.
what is a container in STL?
A template class in the STL that contains a collection of objects and algorithms
What are the 3 sequence containers (that store sequential data) in the STL?
vector
deque
list
What are container adapters?
Containers that do not provide full functionality because their design means some operations may not apply
What are the 3 container adapters?
stack
queue
priority_queue
What are the 4 associative containers?
set
multiset
map
multimap
What does the no-arg constructor do for all STL containers?
copy constructor?
initialise the collection to be empty
initialise a collection to contain copies of the objects in the existing collection
What 4 functions do ALL classes in STL have? What do they do?
size(), empty(), max_size() and swap()
size() returns number of items in collection
empty() returns true if 0 items else false
max_size() returns max possible size for container
swap() takes reference to another container of same type and swaps the contents of the two containers
What does the clear() function do with containers?
Sets the collection to be empty
What does the vector class do? What header is needed?
Parametrised Array with range checking
<vector></vector>