Standard Template Library
Standard Template Library
Standard Template Library
Container Container
Iterator
Algorithm
Objects Iterator
Algorithm
Iterator Iterator
Algorithm
Containers
• A container is a way to store data, either built-in data
types like int and float, or class objects
• The STL provides several basic kinds of containers
– <vector> : one-dimensional array
– <list> : double linked list
– <deque> : double-ended queue
– <queue> : queue
– <stack> : stack
– <set> : set
– <map> : associative array
Containers
Types of containers
•Sequence container
•Associative container
•Derived container
Sequence Containers
max()
max_element()
min()
min_element()
equal()
for_each()- Program example 1-Algorithm
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
void show(int n)
{
cout << n <<" ";
}
int main()
{
int arr[] = { 12, 3, 17, 8 }; // standard C array
vector<int> v(arr, arr+4); // initialize vector with C array
for_each (v.begin(), v.end(), show); // apply function show to each element of
vector v
}
find ()- Program example 2-Algorithm
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int key;
int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array
vector<int> v(arr, arr+7); // initialize vector with C array
vector<int>::iterator iter;
cout << "\nEnter value :";
cin >> key;
iter=find(v.begin(),v.end(),key); // finds integer key in v
if (iter != v.end()) // found the element
cout << "Element " << key << " found" << endl;
else
cout << "Element " << key << " not in vector v" << endl;
}
Iterators
• Iterators are pointer-like entities that are used to access individual elements in a
container.
• Often they are used to move sequentially from element to element, a process
called iterating through a container.
vector<int>
17
array_ vector<int>::iterator
4
23
The iterator corresponding to
12 the class vector<int> is of
the type vector<int>::iterator
size_ 4
Iterators
vector<int> v v.begin()
17
array_
4
23
12 v.end()
size_ 4
Iterators
• One can have multiple iterators pointing to
different or identical elements in the container
vector<int> v i1
array_ 17
4
i2
23
12
i3
size_ 4
Iterator Categories
• Not every iterator can be used with every container for example the list
class provides no random access iterator
• Every algorithm requires an iterator with a certain level of capability. For
example to use the [] operator you need a random access iterator
• Iterators are divided into five categories in which a higher (more specific)
category always subsumes a lower (more general) category.
Iterators and their characteristics
Iterators for various containers