Vector :STL vector container


Vector is one of the stl containers and part of the standard C++.Like the other containers it can safely handle dynamic storage for storing data.It has the internal storage structure same as the dynamic array providing user with a fast and efficient way of accessing the individual data in the storage.It also saves the user from allocating and resizing the storage if the need ever arises because it will handle them automatically for us.The rich features provided by vector and it’s straightforward implementation makes it one of the most used stl containers among the C++ programmers.In this post we will see how to define vector,initialize them and also see how to access them in various way with and without iterators.

Link:Dynamic array object

As mentioned vector uses dynamic array structure ,so the data in vector are stored in consecutive manner;such container are also known as sequence container.A pictorial representation of vector storage is shown below.

STL vector
Note this does not mean it uses dynamic array for it’s implementation.

Link:Sequence container

Defining vector

vector is a template so like any other template when we define vector we will use the template syntax.The template argument can be built-in type or any class object.There is no limitation on which data type a vector can hold,it can even be another vector.

Note include the header <vector> to use the vector container.

class A { } ;

vector<int> vecInt ;///vector that can hold int data

vector<string> vecString ;///vector that can hold string data

vector< A> vecA ;///vector that can hold A class object

vector< vector<int>> vecVec ; /*vector that can hold another vector that can hold int data */


Initializing vector

There are many ways to initialize a vector.A vector can be initialized by initializers or it can be initialized from another vector which usually involve copying of data.

list initialization

When we initialize a vector by initializers we provide the initializers inside a braces.Such initialization method is known as list initialization of vector.The code below shows how to initialize vector using this method.

vector<int> vecInt { 2 , 3 , 4 , 90 } ,
vecInt1{0} ;

vector<string> vecString {“Hi” , “Santa”} ;

vector< vector<int> > vecVec={vecInt , vecInt1 } ; ///a vector holding a vector objects

vecInt now hold the value 2,3,4,90 and vecString holds “Hi” and “Santa” strings.In the third line the argument is a vector so the initializers must be a vector objects.Note here the object supplied as initializers must hold the same type as the type of the vector supplied as the template argument,if not you will get an error.

vector< vector<int> > vecNew={ vecString } ; ///error vecString holds string type

copying vector

A vector can be also initialized from another vector.In such case the copy constructor of the vector is called and it copies the data from the initializer vector.

vector< int> vecNew(vecInt) ; ///copies vecInt data into vecNew

vector< vector<int> > vecNew(vecVec) ; ///work fine

Note when we initialize vector by copying the data from another vector we used a bracket() ,but when we use the list initilaization method we use braces( {} ).Many programmer gets confuse over this difference.



Initializing vector with the same data for a specified number of times

Say we want to initialize vector with 10 same data.Instead of using the list initialization method to write the data repeatedly 10 times we can use a simpler way to achieve the same result.The method requires supplying of two arguments inside a bracket.The first argument determine the number of elements and the second argument is the initializer.

vector<int> veci(5 ,78 ) ;///vec holds 5 integer data with the value 78

vector<string > vecs(3 , “New” ) ;///vecs holds three “New” strings





Empty vector

It is not an error to declare an empty vector,the compiler allows it.To declare an empty vector we simply declare the vector’s object without supplying any initializers.

vector<int> empVec ; //an empty int vector

vector <string> empStr ;///an empty string vector

Note::Do not try to access any element in empty vector you will get an error.

An empty vector does not hold any data so it cannot be used in any way.However,there is a way to insert data into the empty vector using it’s member function,so an empty vector is not completely useless.We will see more about this later.


Accessing vector

The easiest way to access any vector is to use the subscript ‘[]’ after the vector name.The position of the data is specified inside the ‘[ ]‘ bracket.It work more or less like accessing the elements in array.Note you must not try to access the element at invalid position:the position beyond the last element.

vector<int> vecInt { 2 , 3 , 4 , 90 } , vecInt1{0} ;

cout<< vecInt[2] << endl ///access the element in the third position,gives 4
<< vecInt[0] ; ///access the element in the first position,gives 2

/*accessing vector whose type is another vector*/
vector< vector<int> > vecVec={vecInt , vecInt1 } ;

cout<< vecVec[0][1] << endl ///accessing the second element of vecInt,gives 3
<< vecVec[1][0] ; ///accessing the first element of vecInt1 ,gives 0

cout< vecInt[4] ;///dangerous,accessing element at invalid position

When the type is a vector double subscript is used.Doesn’t this look like a 2 dimensional array?

Link:Multidimensional arrays:2D ,3D and 10D array .

we can also change the value of the element using the subscript syntax.

vecInt[3]=89; //work fine

vecInt[4]=80; ///dangerous do not do it

There is no element at the 4th position of the container so, trying to change the value will give you an error.

Using at() function to access the element

There is another way to access the vector element using the member function at( ).When using this function the position of the element is written inside the bracket.

cout<< vecInt.at(2) << endl ///access the element in the third position,gives 4
<< vecInt.at(0) ; ///access the element in the first position,gives 2

front() and back() function

These two functions are used to access the first and the last element of the vector .The front() functions gives the first element and the back() function gives the last element of the vector.

cout<< vecInt.front( ) << endl
<< vecInt.back( ) ;


 


Stop wasting time,earn money($$$) from your website-Join Now!

Inserting element into vector

Suppose you want to add more elements into vector or say you want to add elements into the vector declared as empty previously.In such scenario vector provide a member function ‘push_back( )‘ to add elements into the vector.Note this function add element at the back of the container.

vector<int> vecInt { 2 , 3 , 4 , 90 } ;

vectInt.push_back(123) ;
vectInt.push_back( 234 ) ;

cout<< vecInt[4] << endl //gives 123
<< vecInt[5] ; ///gives 234

To insert element at the specific position of the container we will use iterator.It is shown later.


Understanding vector

The most important features of vector is resizing and reallocating the storage as per required by the user.When you use vector there is no risk of running out of storage.If the vector needs more storage it will reallocate bigger storage to fit the previous elements and the newly added elements.

When the vector reallocate new storage it copies the previous element into the new storage.And vector does this every time it reallocate a new storage.This behavior of vector provides safe and secure environment for using dynamic storage while keeping the memory management process hidden from the user.It allows the user to interact with the container easily using only it’s member functions without needing to make the user worry about the underlying tedious process.

The destruction of the memory is also handle by the vector when it runs out of scope.This is another advantage of using vector over the traditional way of allocating and deallocating memory using the new and delete operator.

Link:New and delete operators


Using iterator with vector

Using iterator we can perform operations in vector much more easily and efficiently.To declare a vector iterator we will use the syntax,

vector< data_type > ::iterator

After an iterator is declare it can point to any vector but with the same type. An example is shown below.The function begin() returns an iterator that points to the first element.

Link What is iterator

vector<string> ::iterator vecStIt ;

vector< string > st{“happy” , “new , “year” };

vecStIt=st.begin() ;///vecStIt points to the begining of the vector st

vector<int> veIt ;

vecStIt=veIt;///error type is different




Using iterator to access the vector element

Before we can use an iterator we must make the iterator point to vector.This can be done by calling the function begin() on the vector as shown in the code above.Once the iterator points to the vector we can perform many operations using the iterator.A code example accessing a vector using an iterator is shown below.

vector< string > st{“happy” , “new , “year” };

vecStIt=st.begin( ) ;

cout<< vecStIt[0] << endl //access the first element
<< vecStIt[2] ;//access the second element


Inserting element in the specific position using iterator

The insert() function can insert element in any position of the container by accepting iterator as one of it’s argument.

The function accept two arguments :the first argument is the iterator that points to the position next to where you want to insert the element and the second is the value of the element you want to insert. In the code below we will try to insert element in the second position using this function.

vector<int> vecInt { 2 , 3 , 4 , 90 } ;

vector<int> ::iterator It ;

//make iterator point to the 3rd position
it=(vecInt.begin( ) +2 );

vecInt.insert( It , 567 ) ;

cout<< vecInt[1] ; ///gives 567

Note the line (vecInt.begin( ) +2 ) ,vecInt.begin( ) returns the first position so we add 2 to make ‘It’ point to the 3rd position.Note you can also replace the first argument ‘It’ with ‘vecInt+2’ directly,it will still work.Both have the same interpretation.


Conclusion

Vector has a lot more other member functions that can perform various operations.Here I have discussed just the basic part of vector,to know more about the other member functions visit the post given under the header <vector> (gonna update soon),in the mean while happy programming!