what’s a vector ?

simply not precisely we can say that the vector is a Dynamic array of variables, struct or objects in which you Insert data at the end ; and this shows a Great difference with arrays in which arrays was created with a fixed size , this is simply why would we use a vector

declaring vectors :

  • vector <int> myvector ;   >> declaring an empty vector of integers
  • vector <float > myvector (5)  >> declaring a vector of  floats having 5 spaces
  • vector <int> myvector (10,1) >> declaring a vector of  integers having 10 spaces all initialized with value 1

Accessing elements in a vectors :

we will focus on two ways to access elements inside the vector

the normal method ” indexing ” []  :

each element in the vector has an index beginning with index 0 for the first element  1 for the second and …etc till the final element and we use  square brackets to write the index inside it

myvector[1] ; // to select the second element
myvector[n-1] ; // to select the final element among n elements

the function   at ()   :

the vector class has a member method called at()  it takes the index of the element and returns the element having this element

myvector.at(1) ;  // to index the second element in the vector 

Are both  the same ? :

actually no  because in the first method  no index range checking happens in the standard library’s vector so an access out of  the array  index bounds is not caught by the compiler for example

vector<int> myvector(5,1) ; cout<< myvector[6] ;

this might be caught by compiler as an error and might not , maybe rubbish is printed

(Range check- ing can be done by using at method ;

ie : myvector.at ( i  )  is the same as a  [  i  ] ,  except that an exception is thrown  if  i  is out-of-bounds

How to fill  a vector :

dealing with vectors is the same as dealing with arrays so to fill a certain element in a vector you say
myvector[5] = 13 ;

Inserting and Deleting Elements inside the vector :

  • push_back() method is used to insert a new row in the vector  // it takes the value of the row as an argument  ex : myvector.push_back(15) ;

  • pop_back() method is used to remove the last row in the vector

click the image for larger view


Getting the size of  a vector  & changing it :

  • size() method is used to return the size of the vector = the number of elements in the vector
  • resize () takes two arguments  the new size as and the value of the new added elements  , if you didn’t add the second argument the new elements will have a value of zero by default