Lesson 17 of 19

Vectors

std::vector

std::vector is a dynamic array from the C++ Standard Library. Unlike C arrays, vectors grow and shrink automatically.

Creating Vectors

#include <vector>
using namespace std;

vector<int> nums;          // empty vector
vector<int> primes = {2, 3, 5, 7};  // with initial values
vector<string> words(3, "hello");   // 3 copies of "hello"

Adding Elements

push_back appends to the end:

vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);

Accessing Elements

cout << v[0] << endl;       // 10 — by index
cout << v.front() << endl;  // 10 — first element
cout << v.back() << endl;   // 30 — last element
cout << v.size() << endl;   // 3 — number of elements

Iterating

Traditional index loop:

for (int i = 0; i < v.size(); i++) {
    cout << v[i] << endl;
}

Range-based for (preferred):

for (int n : v) {
    cout << n << endl;
}

// For non-primitive types, use const reference:
for (const string& s : words) {
    cout << s << endl;
}

Modifying

v.pop_back();          // remove last element
v[1] = 99;            // change element at index 1

Passing to Functions

void printAll(const vector<int>& v) {
    for (int n : v) cout << n << " ";
    cout << endl;
}

Use const vector<T>& to avoid copying and prevent modification.

vector vs C Array

C arrayvector
SizeFixed at compile timeDynamic
Bounds checkingNoneNone (use .at())
CopyManualAutomatic
Pass to functionDecays to pointerPassed by value/ref

Your Task

Create a vector<int> with five elements (10, 20, 30, 40, 50). Print:

  1. The size
  2. The first element
  3. The last element
  4. The sum of all elements
JSCPP loading...
Loading...
Click "Run" to execute your code.