C++•Vectors & Arrays
C++ std::vector (Dynamic Arrays): Methods and Memory
std::vector is the default sequence container in modern C++, offering dynamic resizing and contiguous cache-friendly memory.
Syntax
#include <vector>
std::vector<int> numbers = {1, 2, 3};
numbers.push_back(4);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| push_back(val) | Method | Appends element to end of vector. |
| at(index) | Method | Accesses element with bounds-checking (throws std::out_of_range). |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C++ locally:
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> scores = {92, 85, 88};
// Dynamically append items
scores.push_back(95);
scores.push_back(99);
std::cout << "Vector Size: " << scores.size() << "\n";
std::cout << "Capacity: " << scores.capacity() << "\n";
// Safe bounds-checked access
std::cout << "First Score: " << scores.at(0) << "\n";
std::cout << "Last Score: " << scores.back() << "\n";
// Sum using std::accumulate
int sum = std::accumulate(scores.begin(), scores.end(), 0);
std::cout << "Total Sum: " << sum << "\n";
return 0;
}Expected Output:
Vector Size: 5 Capacity: 6 First Score: 92 Last Score: 99 Total Sum: 459
How It Works: Step-by-Step
- Lines 5-9: Initializes vector and appends elements dynamically.
- Lines 14-15: Uses at() for safe bounds checking and back() for last element.
- Line 18: Computes sum using <numeric> std::accumulate.
Key Concepts
- std::vector elements are contiguous in memory, providing O(1) random access.
- size() is current element count; capacity() is allocated buffer size before reallocation.
- at(i) throws std::out_of_range exception if index is invalid; operator[] does not check bounds.
Common Mistake: Using operator[] beyond vector size
vector[i] does not perform bounds checking and causes undefined memory behavior on invalid indices.
❌ Incorrect
std::vector<int> v; v[0] = 10; // Undefined Behavior: capacity is 0!
✅ Correct
std::vector<int> v; v.push_back(10); // Resizes safely
Related C++ Tutorials & Compiler
C++ std::map and std::unordered_map (Hash Tables)
Learn associative key-value mapping with std::map (Red-Black tree) and std::unordered_map (Hash Table).
C++ std::set and std::pair / std::tuple Explained
Store unique ordered items with std::set and group heterogeneous values with std::pair and std::tuple.
C++ std::string and std::string_view (C++17)
Master text manipulation with std::string and high-performance zero-copy std::string_view.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.