C++ Arrays vs. Vectors: A Short Tutorial

Objective

Understand the key differences between C++ arrays and C++ vectors in terms of features, use cases, and advantages.


1. Overview

FeatureC++ ArrayC++ Vector
DefinitionFixed-size data structure.Dynamic array that resizes automatically.
Header FileNo additional header; built-in type.Requires <vector> header.
SizeFixed at compile-time.Dynamic; can grow or shrink during runtime.
Memory ManagementManual (stack or heap).Automatic; managed by the STL.
SafetyNo bounds checking (undefined behavior on overflow).at() provides bounds checking.

2. Syntax Comparison

Array

#include <iostream>
using namespace std;

int main() {
// Declare and initialize
int arr[5] = {1, 2, 3, 4, 5};

// Access elements
cout << "First element: " << arr[0] << "\n";

// Modify elements
arr[1] = 10;

// Display array
for (int i = 0; i < 5; ++i) {
cout << arr[i] << " ";
}

return 0;
}

Vector

#include <iostream>
#include <vector>

int main() {
// Declare and initialize
vector<int> vec = {1, 2, 3, 4, 5};

// Access elements
cout << "First element: " << vec.at(0) << "\n";

// Modify elements
vec[1] = 10;

// Add and remove elements
vec.push_back(6);
vec.pop_back();

// Display vector
for (int num : vec) {
cout << num << " ";
}

return 0;
}

3. Key Differences

1. Size

  • Array: Fixed size.
    int arr[5]; // Size fixed at 5
  • Vector: Dynamic size.
    vector<int> vec; vec.push_back(10); // Dynamically grows

2. Memory Management

  • Array: User manages memory manually.
    int* arr = new int[5]; // Manual allocation delete[] arr; // Manual deallocation
  • Vector: Memory is automatically managed.

3. Bounds Checking

  • Array: No built-in protection for accessing invalid indices.
    int arr[3] = {1, 2, 3}; cout << arr[5]; // Undefined behavior
  • Vector: Use .at() for bounds checking.
    vector<int> vec = {1, 2, 3}; cout << vec.at(5); // Throws an exception

4. Resizing

  • Array: Cannot resize after declaration.
  • Vector: Resizes automatically.
    vec.resize(10); // Changes size to 10

5. Compatibility with STL Algorithms

  • Array: Requires manual setup.
    sort(arr, arr + 5);
  • Vector: Direct compatibility with STL algorithms.
    sort(vec.begin(), vec.end());

4. When to Use

Use CaseArrayVector
Fixed-size data, performance-critical codeArrays are faster (no overhead).Use vectors sparingly.
Dynamic data or unknown size at compile-timeNot ideal (requires manual resize).Ideal (automatic resizing).
Interfacing with legacy C codeWorks seamlessly.May require .data() for raw pointer access.

5. Exercise

  1. Write a program using arrays to store 5 integers, modify one, and print them.
  2. Convert the program to use vectors and add one more element dynamically.

Conclusion

  • Use arrays when performance and fixed size are key.
  • Use vectors for flexibility, safety, and easier memory management.

Pro Tip: Favor vectors for modern C++ code unless there’s a specific need for arrays.

Scroll to Top