C++ arrays and std::vector store elements in contiguous memory—O(1) random access, cache-friendly like NumPy ndarrays but with explicit types.
Array vs vector
- Fixed array
int a[5]— size known at compile time std::vector<T>— dynamic size,push_back,size()- Iterator range:
for (int x : v)
Common operations
- Index access — O(1)
- Append at end — amortized O(1)
- Insert in middle — O(n) shift
Vector demo
#include
#include
int main() {
std::vector v = {10, 20, 30};
v[1] = 25;
v.push_back(40);
std::cout << v[0] << " " << v.back() << " size=" << v.size() << "\n";
return 0;
}
Important interview questions and answers
- Q: Why contiguous memory?
A: CPU cache locality—sequential access is fast; foundation for SIMD and NumPy-style layouts. - Q: vector vs list?
A: vector for index-heavy workloads; linked list rarely wins on modern hardware due to cache misses.
Self-check
- When use std::vector over raw array?
- Complexity of v[i] access?
Tip: Prefer std::vector for dynamic arrays—cache-friendly like NumPy contiguous buffers.
Interview prep
- vector vs array?
vector dynamic size; array fixed compile-time size.
- push_back cost?
Amortized O(1); occasional O(n) resize.