What are Vectors and Deques?
Vector :- Vector is one type of standard container provided by C++ library. The vector class supports dynamic array i.e it can grow as needed.
- It supports all the functions of an array (i.e accessing array elements using subscript notation) at the same time provides the flexibility of changing size of array at runtime to accommodate changing program conditions.
- Template specification for a vector looks like :
template <class T, class Allocator = allocator <T>> class vector
- Vector has following constructors :
Explicit vector (const Allocator &a = Allocator());
// Constructs empty vector
explicit vector (size_type num, const T &val=T(), const Allocator &a = Allocator());
// constructs vector that has num elements with the value val.
vector (const vector &ob);
// constructs a vector that has same elements as ob.
template <class InIter> vector(InIter start, InIter end, const Allocator &a = Allocator());
// constructs a vector that contains the elements in the range specified by the iterators start and end.
Examples :vector <int> iv; //create zero length int vector
vector <char> cv(5); //create 5 element char vector
vector <char> cv(5, ‘x’); //initializes a 5-element char vector
vector <int> iv; //create a vector from an int vector
- Several member functions are defined by vector. The most commonly used are:
size() : Returns size of vector.
begin() : Returns iterator to the start of vector.
end() : Returns iterator to the end of vector.
push_back() : Puts value to the end of vector (dynamically increase size of vector).
insert() : Adds elements to the middle.
erase() : Removes elements from vector.
Deque :- It’s a double ended queue. That is, it’s a sequence optimized so that operations at both ends are efficient.
- Its template specification is :
template <class T, class Allocator = allocator <T>> class deque
- Here, T is the type of data stored in the deque.
- It has the following constructors :
explicit deque (const Allocator &a = Allocator()); // Constructs empty deque.
explicit deque (size_type num, const T &val=T(), const Allocator &a = Allocator());
// constructs deque that has num elements with the value val.
deque (const deque <T, Allocator> &ob);
// constructs a deque that has same elements as ob.
template<class InIter> deque(InIter start, InIter end, const Allocator &a = Allocator());
// constructs a deque that contains the elements in the range specified by the iterators start and end.
Examples :deque <int> iv; //create zero length int deque.
deque <char> cv(5); //create 5 element char deque.
deque <char> cv(5, ‘x’); //initializes a 5-element char deque.
deque <int> iv; //create a vector from an int deque.