Vector

An vector is very similar to a array, in that it is able to store data within one variable name. The main difference is that a vector is more of a class structure that allows you do to different tasks to it and also it acts similar to a stack FIFO (First In First Out) theory.

Here is SGI vector functions (SGI Vectors)

The vector allows for a dynamic approach of creating and inserting data onto a seemless endless array of data. When a new element is placed onto the vector (push_back), this creates a new block of memory associated with the vector and the value is attached (you can only attached the value the same as the initial setup of the vector, an vector is able to use classes, variables etc to push/pop of the vector/stack).

This is the example code

#include <iostream>
#include <vector>
 
using namespace std;
 
int main()
{
       // create a vector of intergers
       vector<int> vectorInt;
       // push_back, inserts onto the top of the list values
       vectorInt.push_back(2);              // insert 2
       vectorInt.push_back(3);              // insert 3
 
       // a iterator is basically a type of object that can reference part of the vector
       vector<int>::iterator iteratorInt;
 
       // display all of the emplements inside the vector
       for (iteratorInt = vectorInt.begin(); iteratorInt != vectorInt.end(); iteratorInt++)
       {
              cout << *iteratorInt << "\n";              // display what the iterator pointers to 
       }
       // display the size of a vector 
       cout << "size = " << vectorInt.size() << "\n";
 
       // the capacity = how big the vector is, since there has been no pull/remove/erase from the vector
       // then it is the same size.
       cout << "capacity = " << vectorInt.capacity() << "\n";
 
       cout << "Last element " << (int)vectorInt.back() << "\n";              // the last element
       vectorInt.pop_back();                            // delete the last element
       cout << "Last element " << (int)vectorInt.back() << "\n";              // the last element now
 
       cout << "capacity = " << vectorInt.capacity() << "\n";       // capacity is still 2
       cout << "size = " << vectorInt.size() << "\n";              // but the size is 1
 
       cout << "max size = " << vectorInt.max_size() << "\n";       
       return 0;
}

if you save the code as vectorcpp.cpp, then compile and run, the output will be

2
3
size = 2
capacity = 2
Last element 3
Last element 2
capacity = 2
size = 1
max size = 1073741823

and as you can see the with removing the last element from the list (number 3), the size of the vector is reduced, but the capacity is the same since that is how much had been assigned to the vector.

Note : the (int) in front of the vectorInt.back(), will decast the return value into a int(eger) value for the standard console output (std::cout).

Leave a Reply

Your email address will not be published. Required fields are marked *