C++ vector basics

What is a container (in our day to day life)? A container is something that holds some stuffs. In that sense, arrays that we declare in C++ can also be called containers. They hold some values together under one name (the name of the array). Here's how we define an array of ints:

int x[3] = {10, 30, 5};

(You can define an array in other ways too, but let's not get into that here). This array, which is named x, is an array of 3 integers. Now, what if we wanted to add another integer, say 500, to this array, how would we do so? Maybe you're thinking of creating another array with size 4 and copying all the previous values into the new array including the new value we just wanted to put. Or even better, instead of increasing the size to 4, double the size of the new array so that we don't have to resize it frequently. But all this boilerplate code for just a simple operation! What if there was a data structure (a container) which would automatically increase its size as we put items into it and shrink itself as we purge items from it? Welcome std::vector (resides in the <vector> header)! vector is a container which is very similar to an array, in simpler terms, you can think of vectors as an array and you can almost always use it in place of an array. Its a very convenient data type which is provided by the Standard Template Library (STL) in the std namespace. So, let's see how we can define a vector and use it.

#include <iostream>
#include <vector>
using namespace std;

int main() {
 // this is our plain old array
 int x[3] = {10, 30, 5};

 // and this is our new vector!
 // this statement is equivalent to saying,
 // I want a vector named 'v' which will hold 'int' values
 vector<int> v;

 // now, lets insert values into the vector v
 v.push_back(10);
 v.push_back(30);
 v.push_back(5);

 // See? We did not specify the size of the vector
 // while declaring, it automatically grew in size
 // to accommodate for the new values

 // now, we can iterate over the vector just like an array!
 // NOTE: We can get the size of a vector very easily
 // by calling its size() method
 for (int i = 0; i < v.size(); i++) {
  cout << v[i] << endl;
 }

 // EXTRA! When you use a vector, you can use another
 // version of for loop known as for-each, which is available
 // in C++11 and up
 for (int i : v) {
  cout << i << endl;
 }

 return 0;
}

That's it for the basics!

No comments:

Post a Comment

Power function

In C/C++ (and also other languages), we have the built in power function to raise a number to a given power. What if we need to calculate ...