c++_stl
DESCRIPTION
STLTRANSCRIPT
C++ STLContainer types (and algorithms, functions and all STL as well) are defined not in global namespace, but in special namespace called std." Add the following line after your #include and before the code begins:using namespace std;The spirit of the Standard Template Library is the idea of generic programming - the implementation of algorithms or data structures without being dependent on the type of data being handled. For instance, you can use the STL vector container to store a vector (think of it as a resizable array) of any object you desire.1. Vectors Handle own storage when it has to grow unlike an array which is fixed The push_back( ) member function inserts value at the end of the vector, expanding its size as needed. The size( ) function displays the size of the vector. The function begin( ) returns an iterator to the start of the vector. The function end( ) returns an iterator to the end of the vector.vector v; creates an empty vector vvector v(10); creates 10 such empty vectors, similar to a 2D array The empty() function checks if the vector is empty or not Resize() function to resize the vector length Erase() function Another argument for using vectors are that they help avoid memory leaks--you don't have to remember to free vectors, or worry about how to handle freeing a vector in the case of an exception.
vector v(20); for(int i = 0; i < 20; i++) { v[i] = i+1; } v.resize(25); for(int i = 20; i < 25; i++) { v[i] = i*2; } Note that if you use push_back() after resize(), it will add elements AFTER the newly allocated size, but not INTO it. In the example above the size of the resulting vector is 25, while if we use push_back() in a second loop, it would be 30.
vector v(20); for(int i = 0; i < 20; i++) { v[i] = i+1; } v.resize(25); for(int i = 20; i < 25; i++) { v.push_back(i*2); // Writes to elements with indices [25..30), not [20..25) ! Matrix(N, vector(M)); Here we create a matrix of size N*M and fill it with -1. So why use iterators? First, they're a flexible way to access the data in containers that don't have obvious means of accessing all of the data (for instance, maps [to be discussed later]). They're also quite flexible -- if you change the underlying container, it's easy to change the associated iterator so long as you only use features associated with the iterator supported by both classes. Finally, the STL algorithms defined in (to be discussed later) use iterators.
PAIRStemplate struct pair { T1 first; T2 second; }; To create an iterator object, we must specify its type. The type of iterator can be constructed by a type of container by appending ::iterator, ::const_iterator, ::reverse_iterator or ::const_reverse_iterator to it. Thus, vector can be traversed in the following way: vector v;
// ...
// Traverse all container, from begin() to end() for(vector::iterator it = v.begin(); it != v.end(); it++) { *it++; // Increment the value iterator is pointing to } Dont use