1. Technology
Send to a Friend via Email

Using C++ Dynamic Arrays (aka vectors)

What are they for?

By

This is the fifth tutorial in the series Online C++ Tutorial for beginners and is about dynamic array variables. If you want to start at the beginning, begin with the first Online C++ Tutorial.

This is a rewriting of the original C++ tutorials into single page bite size tutorials which can usually be run on either codepad.org or ideone.com.

What are Dynamic Arrays?

In the previous tutorial on C++ arrays, the concept of a fixed size array of items of the same type (where they are all the same be they int, floats, strings, or arrays or objects) was introduced. This is a fixed or static array and it's size is determined at runtime.

Dynamic arrays or as they are better known vectors are arrays that can be resized at run-time. There are some types of data that can be implemented using a static array. For example if you have an enum for the days of the week, then an array of boolean shows which days are working days.

Running this on Ideone // dynarrays.cpp :

#include <iostream>

using namespace std;

        enum days {saturday,sunday,monday,tuesday,wednesday,thursday,friday};
        bool workingdays[] = {false,false,true,true,true,true,true};

bool IsWorkingDay(days aday) {
        return workingdays[aday];
}

int main(int argc, char* argv[])
{
        days day=monday;
        cout << "Is Monday a working day? " << (IsWorkingDay(day) ?"True" : "False") << endl;
        return 0;
}

Outputs:

Is Monday a working day? True

Note though that this example just showed a static array. The workingdays array had a known length and will never need to be resized.

Using the vector template class

Dynamic arrays are created by declaring a vector; you have to add an #include vector in your includes list. This is a template class, which just means that you declare a vector of the type you want. It could be a vector of int, or of a struct or even of an array thogh that would be a bit weird.

Note that there is another template class called a list. The two behave differently. A vector copies elements so they can be accessed via an index just like an array. Items can be added at the front or back very quickly. But they can't be inserted in the vector as quickly. For that a list (which is implemented as a double linked list). In the next tutorial I'll look at lists.

Once you have declared an empty vector you can then start adding items to it. In the example given, it reads a size in from the keyboard using cin then allocates a vector of that size and fill it with that many random numbers and print out the first 10. Then change one of the numbers and again print out the first ten.

// dynarrays.cpp :

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>

using std::cout;
using std::cin;
using std::endl;
using std::vector;

int main(int argc, char* argv[])
{
   srand( time(NULL)) ;
   int numValues;
   cout << "Enter number (Max say 1000)";
   cin >> numValues;
   vector<int> numbers;
   numbers.reserve(numValues) ;

   for (int i=0;i<numValues;i++) {
           int value = rand() % 6 + 1;
           numbers.push_back(value) ;
   }

   cout << numbers.size () << " Elements" << endl;;

   cout << "First 10 Numbers are: ";
   for (int i=0;i<10;i++) {
           cout << numbers.at(i) << " ";
   }
   cout << endl;
   numbers.at( 5 ) = -100;

   cout << "First 10 Numbers are: ";
   for (int i=0;i<10;i++) {
           cout << numbers.at(i) << " ";
   }
   cout << endl;
   return 0;
}

In running this on ideone.com, I learned a valuable lesson. Don't expect reading from cin to work online! It somehow picked up a value of 134516635. However it worked ok.

Important Code

These lines from the example are the important ones so let's look at them.

vector numbers;

This creates an empty vector variable called numbers that holds ints.

numbers.reserve(numValues);

This allocates enough storage to hold the number of ints as specified by numValues. Normally vectors have a small capacity and each time it fills, the capacity is doubled. This reserving of the entire number avoids having to do that.

numbers.push_back(value);

This makes a copy of value and pushes it on the end of the numbers vector. There is also a pop_back() method that removes the last element.

cout

This outputs the element at index i using at(i). The index is zero based, so if there are ten elements then the index goes from 0 to 9.

Note that you can use static array indexing numbers[i] as well as .at(i). Note though that .at() generates an exception that you can catch. The array index [] can go beyond the end of the array, so it's potentially unsafe.

The vector template class is easy to use and has a number of other functions available.

That's it for vector. In the next tutorial I'll look at the List and Array template classes.

  1. About.com
  2. Technology
  3. C / C++ / C#
  4. C++ Programming
  5. Learn C++ Programming
  6. Online C++ Programming Tutorial for Beginners

©2014 About.com. All rights reserved.