C++ Tutorial menu

C++ Arrays and Vectors

Arrays and vectors store many values of the same type under one name.

Arrays

An array has a fixed size that you choose when you create it:

Example

cpp
#include <iostream>
using namespace std;

int main() {
  int marks[4] = {66, 89, 74, 92};

  cout << marks[0] << "\n";
  marks[1] = 90;
  cout << marks[1] << "\n";

  int total = 0;
  for (int m : marks) {
    total += m;
  }
  cout << "Total: " << total << "\n";
  return 0;
}
Output
66
90
Total: 322

Indexes start at 0, and C++ does not check them for you. Reading marks[4] in an array of 4 items gives garbage or a crash.

Vectors

A vector is like an array that can grow and shrink. It is the most used container in modern C++. Include <vector>:

Example

cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
  vector<string> cart = {"Milk", "Bread"};
  cart.push_back("Eggs");
  cart.push_back("Tea");

  cout << "Items: " << cart.size() << "\n";
  cout << "First: " << cart.front() << "\n";
  cout << "Last: " << cart.back() << "\n";

  cart.pop_back();   // remove Tea
  for (const string& item : cart) {
    cout << "- " << item << "\n";
  }
  return 0;
}
Output
Items: 4
First: Milk
Last: Tea
- Milk
- Bread
- Eggs

Common Vector Functions

FunctionWhat it does
v.push_back(x)Adds x at the end
v.pop_back()Removes the last item
v.size()Number of items
v[i]Item at index i (no check)
v.at(i)Item at index i, with a safety check
v.empty()true if there are no items
v.clear()Removes all items

Arrays vs Vectors

ArrayVector
SizeFixedCan change
Add itemsNot possiblepush_back
Knows its sizeNot easilysize()
Best forSmall fixed listsAlmost everything else

Sorting and Finding

The <algorithm> library works with vectors:

Example

cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
  vector<int> prices = {499, 120, 850, 300};
  sort(prices.begin(), prices.end());

  for (int p : prices) {
    cout << p << " ";
  }
  cout << "\n";
  cout << "Max: " << *max_element(prices.begin(), prices.end()) << "\n";
  return 0;
}
Output
120 300 499 850 
Max: 850

Two-Dimensional Data

Example

cpp
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
cout << grid[0][2] << "\n";   // prints 3

Exercise

Exercise

Which function adds an item to the end of a vector?

Learn C++ with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp