Trusted answers to developer questions

C++ Vector vs. Array

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

svg viewer
  • Dynamic in nature. The size automatically changes as elements are added or removed.
  • Fixed in size. Once the array is initialized with values and is allocated a space in the memory you cannot change its size unless it is a dynamic array.
  • Occupies a lot of memory, due to being dynamic in nature. A typical vector implementation grows by doubling its allocated space rather than incrementing it by 1. Reallocating memory is usually an expensive operation in vectors.
  • A memory efficient data structure where each element in an array occupies a single space. The array only uses its allocated space once it is initialized, after which it does not need to change its size due to it being non-dynamic.
  • Syntax to initialize a vector of integers in C++ is:

    vector<int> vec;

    You add elements in the vector gradually by using the push_back(n) function.

  • Syntax to initialize a basic array of integers in C++ is:

    int arr[4] = [3, 6, 1, 8];

  • Better suited if one needs to add or remove elements from a list frequently.
  • Better suited for frequent access of elements irrespective of their position. This is due to their contiguous property and index-based structure.
  • Vector is a template class in C++, that is, a vector template class needs to be shipped from the C++ library in order to use the vector functions.
  • Basic lower level data structure which does not need to be shipped from a template class.

RELATED TAGS

c++
vector
array
vectors
arrays
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?