Vectors in C++ tutorial


This is a short brief overview on the basics of Vectors in C++ and how to use them. Vectors in C++ are a type of data structure that are like an array, however they are “smarter”. They can resize (with ease, and allocate however much space is needed to store something to it), you can get actual size of the container, have access to more functions, and have fast random access compared to the non-resizeable array. This post is not meant to be in depth, but it should guide you if you are a beginner on this concept.

Basics…

  • Declare a vector like so:
    vector<Type> v;
  • Type stands for the object type, you need to always specify an object type when you are declaring a vector
  • You don’t need to specify a size for the vector, because when you insert it will automatically create space to store a value
  • To access/modify an index within a vector: operator[]
  • However, if you want to specify a size for the vector, you can do so like this:
    v.reserve(5);

Insertion with Vectors:

  • Insertion can be done a few ways, you can use .insert() or .push_back()
  • .insert(): this method inserts values into the vector, it takes an iterator object, and an object to insert as arguments
    • An iterator in a vector, usually is at the first or last index: .begin() or .end(), is used to navigate through the vector, you can also create a separate iterator to work with like so: vector<int>::iterator it;
    • You need an iterator to use .insert(), for example, if we were to populate a vector with 10 spaces using a loop (you can also create a separate iterator for a vector):
      //populate 5 spaces of the vector with integers
          vector<int> collection;
          int x = 5;
          for(int i = 0; i < 5; i++)
          {
              collection.insert(collection.begin() + i, x+=5);
              //to insert, you need an iterator, collection.begin() starts at position 0, we add i to move through
          }
          vector<int>::iterator it;//you can also declare a separate iterator to use for a vector and use that
          it = collection.begin(); //this points to the first element in the vector
          it = collection.end(); //this points to the last element in the vector
      
  • .push_back works like the stack .push(), except, .push_back() inserts at the end of the vector

Deletion with Vectors:

  • Removing from a vector can be done a few ways, you can use .erase(), clear(), or pop_back()
  • .erase(): similar to insert, erase() takes only 1 iterator argument, to remove a value from like so:
  • clear(): takes no parameters, returns void, and essentially erases everything from the vector, so no elements exist and the vector has size 0
  • pop_back(): this function works much like the stack version of pop(), except when we use the vector version, it removes from the back

Other functions:

  • clear(): removes all elements within the vector, therefore size becomes 0, returns void, no parameters
  • capacity(): displays the size of the storage space currently allocated for the vector, returns an integer, no parameters
  • swap(): swaps the contents of one vector object to another vector object and vice versa
  • size(): returns the size of the vector based on how many elements there are, no parameters
  • at(): this function takes a index of the vector, and replaces the index with a value specified like so: v.at(0) = 64; //replaces whatever is at spot 0 with the value 64
  • assign(): assign returns void, and takes two parameters, a size, and a value. This method will set all the specified spaces with the specified value like so:
    vector<int> A;
    A.assign(10, 32);//this will create 10 spaces for the vector called 'A', and fill all those spaces with the value 32
    
  • swap(): this function returns void and takes a vector reference, it takes two vectors, and swaps all the contents and size(s) between them, example:
      vector<int> foo (3,100);   // three ints with a value of 100
      vector<int> bar (5,200);   // five ints with a value of 200
    
      foo.swap(bar);
      // foo now has 200,200,200,200,200
      // bar now has 100,100,100
    

Sample code of using a Vector in C++:

#include "main.h"
#include <iostream>
#include <vector>
#include <windows.h>

using namespace std;

void WriteToScreen(vector<int> &v);
int main()
{
    vector<int> collection;//declare a vector of type int

    //collection.reserve(5);//this is optional, you can either reserve a number of spaces
    //or you can just insert values without reserving space

    //populate 5 spaces of the vector with integers
    int x = 5;
    for(int i =0; i < 5; i++)
    {
        collection.insert(collection.begin() + i, x+=5);
        //to insert, you need an iterator, collection.begin() starts at position 0, we add i to iterate
    }
    vector<int>::iterator it;
    WriteToScreen(collection);
    //remove some values
    for(int i = 0; i < collection.size(); i++)
    {
        if(i == 0 || i == 3 || i == 5)//delete values that are at indexes 0, 3, and 5
        {collection.erase(collection.begin() + i);}
    }
    WriteToScreen(collection);
    cout<<collection.size()<<endl;//gets the size of the vector
    cout<<collection.front()<<endl;//gets the first value in the vector @ index 0
    cout<<collection.back()<<endl;//gets the value at the end of the vector @ index Size - 1
    collection.resize(2);//resizes the vector to the specified size
    WriteToScreen(collection);
    collection.push_back(100);//insertion from the end of the vector (works like a stack)
    WriteToScreen(collection);
    collection.pop_back();//removes from the end of the vector (pops like a stack)
    WriteToScreen(collection);
    cout<<collection.capacity()<<endl;//displays the current capacity of the vector
    collection.at(0) = 64;//put the number 64, at index 0 of the vector, replacing the older value
    WriteToScreen(collection);

    return 0;
}
//this function displays the vector to the window, it takes a vector reference of type int
void WriteToScreen(vector<int> &v)
{
    for(int i = 0; i < v.size(); i++)
    {cout<<v[i]<<" ";}
    cout<<endl;
}

Examples of Vector operations

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s