Understanding Vectors in C++: Key Features

Vectors are Just like arrays but with some special Features that gives you some flexibility i.e If you want to add a element at a later stage ( like a dynamic array) etc.

We define a Vector as
vector<data typevariable_name(size);
 where
Example :  vector temperature(7);

It defines a vector called temperature which is of type double and stores value of temperature recorded for 7 days.
What if at a later stage we want to store the temperature for the whole month.That’s where vector’s come handy !!!

  •  vector is the keyword to define a vector
  •  data type can be anything ranging from int,double,string
  • variable_name can be any valid variable name
  • size is the initial size that can be provided

Have a look at this video it will surely help.

Let us take the following program demonstrates the vector container (a C++ Standard Template) which is similar to an array with an exception that it automatically handles its own storage requirements in case it grows:

#include

#include

using namespace std;

void printv(vector b)

{

for(int i=0;i

{

cout<

}

}

int main()

{

vector<int> v(3);

v[0]=10;

v[1]=22;

v[2]=5;

v.push_back(7);

cout<

cout<

cout<

printv(v);

return 0;

}

Here are following points to be noted related to various functions we used in the above example:

1) The push_back( ) member function inserts value at the end of the vector, expanding its size as needed.

2) The size( ) function displays the size of the vector

3) The function front( ) returns the start of the vector.

4) The function back( ) returns the end of the vector.

5) The function at( ) returns element at a particular position.

Leave a comment