In C++, vector is a collection class that allows you store any type of values. It is similar to array. However, vector is dynamic. Its size can grow at run time. In addition, by using vector, you can simply add new items to, delete items from, and insert new items in to, the vector.
The vector class has the following constructors that can be used to create vector objects so that they are ready to store items.
-explicit vector(const allocator_type& __a) creates an empty vector with the default allocator.
-explicit vector(size_type __n) creates a vector object with specifying the number of items to be stored in the vector.
-vector(size_type __n, const _Tp& __value, const allocator_type& __a) creates an vector object with specifying the number of items to be stored in the vector, and initial items.
-vector(const vector<_Tp, _Alloc>& __x) creates a vector object from a specified vector object.
The commonly used members of the vector class are push_back(), pop_back(), erase(), insert(), begin(), end(), and size(). The push_back() allows you to add a new item to end of the vector. In contrast, the pop_back() will remove the last item from the vector. By using the erase(), you can delete an item at the specified position from the vector. The insert() allows you to insert an item to the specified position of the vector. The begin() and end() read the first and the last items of the vector respectively. The size() member returns the number of items stored in the vector.
Here is an example of using vector in C++:
using namespace std;
int main(int argc, char *argv)
//create an empty vector
//add 10 items to the vector object
//display the items of the vector by using for loop (like an array)
//insert 34 at the 5th position
//remove the 3th item of the vector
//display the items of the vector by using iterator
Posted by: Dara | post date: 12-20-2013 | Subject: C++ Programming Language
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages: