9. Dynamic Arrays and Vectors

About this Tutorial –

Objectives –

This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.


Students who are new to object orientation (or programming) and need to learn C++.


No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.


The C++ course covers these topics and more:

  • Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
  • Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
  • Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures

Download Solutions

Java tutorial


Estimated Time – 0.5 Hours

Not what you are looking? Try the next tutorial – Lists and Maps

Lab 1: Recap arrays

Lab 1: Recap arrays
  1. What is an Array?
    • An array is:
      • A fixed-size collection of items
      • All the items are the same type
    • Arrays are good for:
      • Fixed-size collections, when you know the size in advance
      • Accessing elements at random positions (using [index] notation)
    • Arrays are not good for:
      • Variable-size collections (you can’t resize an array after you’ve created it)
      • Inserting elements in the middle (you would have to manually shuffle all the other elements down one position, to make a gap)
  2. Creating an Array
    • Specify the type of the array elements, and the number of elements
      • The number must be constant (i.e. you can’t use a variable)
    • You can create an array of simple types (e.g. ints) and arrays of objects (e.g. Persons)
      int examMarks[8];
      class Person
       void Display() const;
      Person footballersForSwansTeam[11];
  3. Using an Array
    • Access array elements by index position (first element is [0], last element is [n-1])
    • Typically use a for-loop to iterate over all elements:
      for (int i = 0; i < 8; i++) {  cout << "Exam mark " << " is " << examMarks[i] << endl; } for (int i = 0; i < 11; i++) {  footballersForSwansTeam[i].Display(); }
  1. Using a fixed-size array
    • In Visual Studio, create a new C++ project named ArraysVectorsApp in the student folder
    • Implement a class named Employee, to hold an employee's name and salary. Also add the following members to the class:
      Employee::Employee(const string & name, double salary)
      : name(name), salary(salary){

      • A fixed-sized array to hold exactly 12 integers, representing the employee's "ratings" each month (you know, when they meet with their manager)
        int ratings[12];
      • A method to set a rating (the method needs an integer for the array index, plus an integer for the rating)
         if (index >= 0 && index < TOT_MONTHS)  {   ratings[index] = value;   return true;  }  else  {   return false;  } }
      • View code file.
      • A method to get a rating
        int Employee::GetRating(int index) const
         if (index >= 0 && index < TOT_MONTHS)  {   return ratings[index];  }  else  {   return 0;  } }
      • View code file.
    • In main(), create an Employee object and tests its "ratings" features
      Employee e(name, 300);
      e.SetRating(0, 5);
      e.SetRating(1, 4);
      e.SetRating(2, 4);
      e.SetRating(3, 3);
      e.SetRating(4, 5);
      e.SetRating(5, 5);
      e.SetRating(6, 4);
      e.SetRating(7, 4);
      e.SetRating(8, 5);
      e.SetRating(9, 5);
      e.SetRating(10, 3);
      e.SetRating(11, 5);
      cout << "Ratings each month: " << endl;
      for (int i = 0; i <TOT_MONTHS; i++)
       cout << e.GetRating(i) << endl;
    • View code file.

Lab 2: Dynamic arrays

Lab 2: Dynamic arrays
  1. What is a Dynamic Array?
    • A dynamic array is the same as a normal array, except:
      • You create it using new[]
      • You can decide its size at run time
      • It remains allocated forever, until you delete it with delete[]
    • Dynamic arrays are better than "normal" arrays when:
      • You don't know the size in advance...
      • You can ask the user how many elements they want, and then create the array with that size
    • Note: these restrictions still apply, as for "normal" arrays:
      • You can't resize it after you've created it
      • Not good for inserting elements in the middle
  2. Creating a Dynamic Array
    • Here's a reminder of how to create a "normal" array:
      int examMarks[8];
      Person footballersForSwansTeam[11];
    • And here's how to create a "dynamic" array
      • Use new[] to allocate an array of n elements (on the heap)
      • It automatically calls the default constructor on each object
      • It returns a pointer to the first element
        int *marks = new int[n]; // Can use variables for array size now
        Person *peeps = new Person[n]; // Can create array of objects
  3. Using a Dynamic Array
    • Here's a reminder of how to use a "normal" array:
      for (int i = 0; i < 8; i++)  cout << "Exam mark " << " is " << examMarks[i] << endl for (int i = 0; i < 11; i++)  footballersForSwansTeam[i].Display();
    • You can use dynamic arrays in exactly the same way
      • Due to the way pointers/arrays work in C++
        for (int i = 0; i < n; i++)  cout << "Exam mark " << " is " << marks[i] << endl; for (int i = 0; i < n; i++)  peeps[i].Display();
  4. Deleting a Dynamic Array
    • You must remember to delete dynamic arrays, using delete[]
      • If you don't, the memory will never be reclaimed (memory leak!)
      • Note: You must use delete[] for dynamic arrays (not delete)
    • So here's how to delete a "dynamic" array
      • Use delete[] on the pointer
      • It automatically calls the destructor on each object
      • It then frees up the storage for the dynamic array
        delete [] marks;
        delete [] peeps;
  1. Using a dynamic array
    • Enhance the Employee class, to hold the employee's "n" previous companies:
      • Implement the "previous companies" as a dynamic array to hold "n" strings
        string * companies;
      • The constructor should take an integer specifying the number of elements. The constructor should then loop round asking the user to enter each string during construction
        Employee::Employee(const string & name, double salary, int companiesTotal)
         : name(name), salary(salary), companiesTotal(companiesTotal)
         companies = new string[companiesTotal];
        void Employee::SetCompanies()
         for (int i =0; i < companiesTotal; i++)  {   cout << "Please enter company " << i+1 << " name: ";   cin >> companies[i];
        void Employee::DisplayCompanies() const
         for (int i = 0; i < companiesTotal; i++)  {   cout << "Company " << i+1 << " name: " << companies[i] << endl;  } }
      • View code file.
    • In main(),write code to test this new functionality
      employee e(name, 300, 3);
      cout << "Companies: " << endl; e.DisplayCompanies();
    • View code file.

Lab 3: Using vector

Lab 3: Using vector
  1. What is vector?
    • vector is a standard C++ class
      • Defined in <vector>
      • You also need a using namespace std;
    • Similar in concept to a resizable array
      • You can create an empty vector initially
      • Then add items at the end (it automatically expands)
    • You can also:
      • Ask the vector its size
      • Access elements at particular elements using []
      • Iterate through all the elements, etc...
      • Remove items
      • Etc...
  2. Creating a vector
    • When you create a vector object, you must specify what type of elements it will contain, using <...> notation
      • i.e. vector is an example of a "template class"
      • We'll investigate template classes in detail later in the course
    • Here are some simple examples
      #include <vector>
      using namespace std;
      int main ()
       vector<int>  marks;  // Empty vector of ints.
       vector<Person> people; // Empty vector of Persons. 
    • You can also create a vector and pre-populate it with elements
      vector<int> marks(8, 100); // Eight ints with value 100
  3. Adding Items to a vector
    • You add items to the end of a vector
      • Using the push_back() method
      • Automatically expands vector internally
      • Pushes a copy of your value into the vector, at the end
        int value;
        Person aPerson;
  4. Removing Items from a vector
    • You remove items from the end of a vector
      • Using the pop_back() method
      • Automatically decreases the vector size by 1
      • Doesn't actually give you the item though...
  5. Accessing Elements in a vector
    • You can access elements using []
      • But be careful, if you index off the end, an exception occurs
        marks[2] = 97;
        cout << marks[2];
    • You can access an element using at()
      • Again, be careful about out-of-bound errors
        marks.at(2) = 180;
        cout << marks.at(2);
    • To access the first/last elements:
      • Use front() and back()
        cout << marks.front(); cout << marks.back();
  6. Looping through Elements
    • The easiest way to iterate over a vector:
      for (int i = 0; i < marks.size(); i++) {  cout << marks[i]; } for (int i = 0; i < people.size(); i++) {  people[i].Display(); }
    • There's also a mechanism known as "iterators"
      • These are like "smart pointers"
      • Allow you to step through a collection (vector, list, etc)
      • More flexible in advanced situations
        vector<int> marks;
        vector<int>::iterator iter;   // Create an iterator, to iterate over a vector<int>.
        for (iter = marks.begin(); iter < marks.end(); iter++) // Loop through vector.
         cout << *iter;        // Get contents at the current position.
        vector<Person> people;
        vector<Person>::iterator iter; // This one will iterate over a vector<Person>.
        for (iter = people.begin(); iter < people.end(); iter++) // Loop through vector.
         (*iter).Display();      // Or say iter->Display() if you prefer.
  7. A Closer Look at Iterators
    • Each STL container has its own nested iterator classes
      • iterator - gives pointer-like access to the elements
      • const_iterator - gives const-pointer-like access to elements
    • T9P1

    • Plus:
      • reverse_iterator
      • const_reverse_iterator
  1. Using a vector
    • Enhance the Employee class, to hold "todo" items for the employee:
      • Implement the "todo" collection as a vector<string>
        vector<string> todo;
      • Write methods to "add" a todo item, and to "complete" a todo item (the employee always completes the "last" item in the vector - like a stack, where the last item in is the first item processed)
        void Employee::AddTodo(const string & item)
        void Employee::TodoComplete()
      • View code file.
      • Also write methods to display all tasks, and to say if the employee is overworked (in my company, I'm overworked if I have more than 2 things to do
        void Employee::DisplayTodoList() const
         int size = todo.size();
         for (int i = 0; i < size; i++)  {   cout << todo[i] << endl;  } }
      • View code file.
    • In main(),write code to test this new functionality
      Employee e(name, 300, 3);
      cout << "Todo list: " << endl; e.DisplayTodoList(); cout << endl; e.TodoComplete(); e.DisplayTodoList();
    • View code file.


Well done. You have completed the tutorial in the C++ course. The next tutorial is

10. Lists and Maps

Back to beginning
Copyright © 2016 TalkIT®

If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top