Friday, June 8, 2012


The vector class supports a dynamic array. This is an array that can grow as needed.

The template specification for vector is shown here:
template <class T, class Allocator = allocator<T> > class vector
где Т это тип данных, который будет сохранен и Allocator specifies the allocator, which
defaults to the standard allocator.

vector has the following constructors:

explicit vector(const Allocator &a = Allocator( ) );
explicit vector(size_type num, const T &val = T ( ),
const Allocator &a = Allocator( ));
vector(const vector<T, Allocator> &ob);
template <class InIter> vector(InIter start, InIter end,
const Allocator &a = Allocator( ));

The first form constructs an empty vector. The second form constructs a vector that
has num elements with the value val. The value of val may be allowed to default. The
third form constructs a vector that contains the same elements as ob. The fourth form
constructs a vector that contains the elements in the range specified by the iterators
start and end.

For maximum flexibility and portability, any object that will be stored in a vector
should define a default constructor. It should also define the < and == operations.
Some compilers may require that other comparison operators be defined. (Since
implementations vary, consult your compiler's documentation for precise information.)
All of the built-in types automatically satisfy these requirements.

Declaration of vectors:

vector<int> iv; // create zero-length int vector
vector<char> cv(5); // create 5-element char vector
vector<char> cv(5, 'x'); // initialize a 5-element char vector
vector<int> iv2(iv); // create int vector from an int vector

The following comparison operators are defined for vector:
==, <, <=, !=, >, >=, []

The Container Classes

Это STL objects that actually store data.

Container                   Description                 Required Header
bitset                             A set of bits.                       <bitset>
deque                        A double-ended queue.          <deque>
list                                   A linear list.                         <list>
map                        Stores key/value pairs in             <map>
                            which each key is associated
                                  with only one value.
multimap             Stores key/value pairs in which       <map>
                           one key may be associated with
                                 two or more values.
multiset                  A set in which each element          <set>
                            is not necessarily unique.
priority_queue             A priority queue.                   <queue>
queue                                A queue.                        <queue>
set                      A set in which each element             <set>
                                   is unique.
stack                              A stack.                             <stack>
vector                        A dynamic array.                     <vector>

Other STL Elements

Each container has defined for it an allocator. Он управляет распределением памяти для container. The default allocator is an object of class allocator, but you can define your own allocators.

Некоторые algorithms и containers используют special type of function called a predicate.
There are two variations of predicates: unary and binary. A unary predicate takes one argument, while a binary predicate has two. These functions return true/false results. But the precise conditions that make them return true or false are defined by you. For the rest of this chapter, when a unary predicate function is required, it will be notated using the type UnPred. When a binary predicate is required, the type BinPred will be used. In a binary predicate, the arguments are always in the order of first,second. For both unary and binary predicates, the arguments will contain values of the type of objects being stored by the container.

Some algorithms and classes use a special type of binary predicate that compares two elements. Comparison functions return true if their first argument is less than their second. Comparison functions will be notated using the type Comp.

Two other entities that populate the STL are binders and negators. A binder binds an argument to a function object. A negator returns the complement of a predicate.

One final term to know is adaptor. In STL terms, an adaptor transforms one thing into another. For example, the container queue (which creates a standard queue) is an adaptor for the deque container.


STL базируется на containers, algorithms, iterators.

Containers - объекты, которые содержат другие объекты.
Sequence containers: vector, deque, list
Associative containers(based on keys): map

Each container class defines a set of functions that may be applied to the container.

Algorithms act on containers. (initialization, sorting, searching and transforming the contents of containers).

Iterators are objects that act, more or less, like pointers. They give you the ability to cycle through the contents of a container in much the same way that you would use a pointer to cycle through an array.

Есть 5 типов итераторов:

Random Access - Store and retrieve values. Elements may be accessed randomly.
Bidirectional - Store and retrieve values. Forward and backward moving.
Forward - Store and retrieve values. Forward moving only.
Input - Retrieve, but not store values. Forward moving only.
Output - Store, but not retrieve values. Forward moving only.

Iterators are handled just like pointers. You can increment and decrement them. You
can apply the * operator to them. Iterators are declared using the iterator type defined
by the various containers.

The STL also supports reverse iterators. Reverse iterators are either bidirectional or
random-access iterators that move through a sequence in the reverse direction. Thus, if
a reverse iterator points to the end of a sequence, incrementing that iterator will cause
it to point to one element before the end.

Term    Represents
BiIter - Bidirectional iterator
ForIter - Forward iterator
InIter  - Input iterator
OutIter - Output iterator
RandIter - Random access iterator

Потоковые указатели

Это get() и put() указатели. get() - текущая позиция чтения. put() - текущая позиция записи.

ifstream обладает указателем get()
ofstream обладает указателем put()
fstream обладает обоими указателями.

Чтение из файла

#include <fstream>
#include <iostream>
using namespace std;

int main()

ifstream dragons("dragons.txt");

char buffer[50];

cout << "Ошибка, невозможно открыть файл";
exit(1);//1 так как возникла ошибка

dragons.getline(buffer, 49);// getline() для чтения из файла в buffer
cout << buffer << endl;


int a;
cin >> a;

return 0;

Запись в файл

//Write text to txt file.

#include <fstream>

using namespace std;

int main()
ofstream dragons("dragons.txt"); //конструктор то же самое что и метод open()

if(dragons.is_open())//проверяем корректность открытия файла
dragons << "Медный дракон" << endl
<< "Бронзовый дракон" << endl
<< "Серебряный дракон" << endl
<< "Золотой дракон" << endl;


return 0;

open(filename, mode) эти связать объект файлового потока с рабочим файлом.