Thursday, 9 July 2015

Vectors

https://github.com/prasanthlouis/C-equivalent-to-Cracking-the-Coding-Interview

Vectors are pretty cool. They're more of a replacement for the original arrays in C++.


Let's check them out!


So normally you'll have a static array such as

int number[20];

As you can see, your array has a constant size.

What about dynamic arrays in C++?

Well, the size parameter doesn't have to be constant.

int number[size], where size is defined as a non constant variable.

However dynamic arrays come at the disadvantage that they have to be cleared from the memory when you're done using them.

Eg. delete[] array

Now vectors combine the advantage of both the above arrays.
They can use a non-constant size attribute for the array (like dynamic) but you don't need to clear the memory when you're done using them (like static).

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

int main()
{
    int i;
   vector<int> intarr(10);
   for(i=0;i<10;i++)
   intarr[i]=i;
 
   for(i=0;i<10;i++)
   cout<<intarr[i];
 
   return 0;
}


The rest of the syntax, is pretty much the same. But it should be said, that vectors tend to use a bit more memory due to the dynamic allocation. In fact, if you declared your variable size=20, the actual memory allocation is a bit bigger, just in case you need to change your memory size dynamically later on.

No comments:

Post a Comment