WeCodeAcademy

C++ Arrays and Vectors

A plain array has a fixed size. A std::vector is a resizable array and is usually the better choice.

ExampleC++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
  int nums[3] = {10, 20, 30};
  cout << nums[1] << endl;

  vector<int> v = {5, 2, 9};
  v.push_back(1);
  sort(v.begin(), v.end());
  for (int x : v) cout << x << " ";
  cout << endl;
  cout << "size " << v.size() << ", last " << v.back() << endl;
  return 0;
}
Output
20
1 2 5 9 
size 4, last 9
Quick check

What is the advantage of vector over a plain array?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.