We’re comparing C++ arrays vs C++ vectors (from STL).


1️⃣ Basic Definition

FeatureArrayVector
TypeBuilt-in language typeSTL container (std::vector)
SizeFixed at compile-time or runtime (C-style)Dynamic, grows/shrinks automatically
MemoryContiguous memoryContiguous memory internally, manages memory automatically
HeaderNone#include <vector>
Syntaxint arr[5];std::vector<int> v;

2️⃣ Memory & Size

Array:

int arr[5];  // size = 5, cannot change
  • Size is fixed
  • If you try arr[10] = 7; → Undefined behavior
  • Stack allocated (or static/global)

Vector:

#include <vector>
std::vector<int> v;
v.push_back(10);
v.push_back(20);
  • Size is dynamic
  • Automatically resizes when adding elements
  • Allocates memory on heap internally

3️⃣ Access Elements

Both use indexing:

arr[0]      // Array
v[0] // Vector
v.at(0) // Vector with bounds checking
  • v.at(i) throws exception if out of bounds → safer than array

4️⃣ Advantages & Disadvantages

Array

✅ Pros:

  • Very fast (no memory management overhead)
  • Simple, low-level, minimal footprint

❌ Cons:

  • Fixed size → cannot grow
  • No built-in functions (push, pop, insert)

Vector

✅ Pros:

  • Dynamic size → easy to use
  • Many helper functions: push_back(), pop_back(), size(), clear()
  • Safer with .at() bounds checking

❌ Cons:

  • Slight overhead for dynamic memory allocation
  • Slightly slower than raw arrays in tight loops

5️⃣ When to use which

ScenarioRecommendation
You know the size at compile-time & performance-criticalArray
You need dynamic size & convenienceVector
Need STL algorithms (sort, find)Vector (works seamlessly)

6️⃣ Example

#include <iostream>
#include <vector>
#include <algorithm>int main() {
int arr[3] = {1, 2, 3};
std::cout << "Array: ";
for(int i = 0; i < 3; i++) std::cout << arr[i] << " ";
std::cout << "\n"; std::vector<int> v = {1, 2, 3};
v.push_back(4); // Dynamic size
std::sort(v.begin(), v.end()); // STL algorithms
std::cout << "Vector: ";
for(int x : v) std::cout << x << " ";
}

Output:

Array: 1 2 3 
Vector: 1 2 3 4

7️⃣ Key Takeaway

  • Array → Low-level, fixed size, very fast
  • Vector → Modern C++ choice, flexible, safer, integrates with STL

💡 Most useful in real-world C++ projects: std::vector, because almost always you need dynamic size and STL support. Arrays are mostly used for performance-critical or embedded scenarios.