DEV Community

Igor
Igor

Posted on

Vectors in C++

  • Vectors

    • What they are
    • Advantages vs arrays
    • Declaration and initialization
  • Suppose we want to store test scores for my school

  • I have no way of knowing how many students will register next year

  • Options:

    • Pick a size that you are not likely to exceed and use static arrays
    • Use a dynamic array such as vector

What is a vector?

  • A vector is a sequence of elements that you can access by an index. It is a container in the C++ Standard Template Library (STL)
  • An array that can grow and shrink in size at execution time
  • Provides similar semantics and syntax as arrays
  • Very efficient
  • Can provide bounds checking
  • Can use lots of functions like sort, reverse, find, and more.

Declaring

#include <vector>
using namespace std;

vector <char> vowels;
vector <int> test_scores;

// Using a constructor initialization syntax
vector <char> vowels(5);
vector <int> test_scores(10);
Enter fullscreen mode Exit fullscreen mode
  • Unlike arrays, the 10 integers will automatically be set to 0.

Initializing

vector <char> vowels {'a', 'e', 'i', 'o', 'u' };
vector <int> test_scores {100, 90, 88, 79, 93};
vector <double> hi_temperatures (365, 85.0); // (initial_size, initial_value)
Enter fullscreen mode Exit fullscreen mode

Characteristics

  • Dynamic size
  • Elements are all the same type
  • Stored contiguously in memory
  • Individual elements can be accessed by their position or index
  • First element is at index 0
  • Last element is at index size-1
  • [ ] - no checking to see if you are out of bounds
  • Provides many useful function that do bounds check
  • Elements initialized to zero
  • Very efficient
  • Iteration (looping) is often used to process

Top comments (0)