Using vector

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++:

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char *argv[])
   //create an empty vector
   vector<int> v;
   //add 10 items to the vector object
   for(int i=0;i<10;i++){
   //display the items of the vector by using for loop (like an array)
   for(int i=0;i<v.size();i++){
   //insert 34 at the 5th position
   vector<int>::iterator p=v.begin();  
   //remove the 3th item of the vector
   //display the items of the vector by using iterator
   vector<int>::iterator it=v.begin();
   return EXIT_SUCCESS;

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:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.