How to Add to an Array

beginner c++17 containers vector

Related: What is Vector

In C++ arrays are fixed size, meaning you cannot change the array’s size after creating it. Arrays that can change their size are known as std::vector in C++. To add to a std::vector you use the push_back method. In other languages this may be called append or push.

#include <vector>
#include <iostream>

int main() {
  std::vector<int> v;
  v.push_back(42);

  std::cout << v.size() << "\n";
  std::cout << v.back() << "\n";
}
1
42

To remove from the end of an array call pop_back.

#include <vector>
#include <iostream>

int main() {
  std::vector<int> v{1, 2, 3};
  v.pop_back();

  std::cout << v.size() << "\n";
  std::cout << v.back() << "\n";
}
2
2

For more C++ By Example, click here.