C++ Arrays, std::string, string_view & std::vector Masterclass
Welcome to Phase 7 (Chapter 7): C++ Arrays, std::string, string_view & std::vector Masterclass! Dynamic sequence containers form the backbone of modern software. In this guide, you will master C-style arrays vs std::array, std::string API manipulation, zero-allocation std::string_view (C++17), and dynamic std::vector operations.
| Container | Memory Allocation | Size Fixed or Dynamic? | Bounds Checked (.at())? |
|---|---|---|---|
C Array (int arr[5]) | Stack / Contiguous | Fixed at compile time | No (Danger of out-of-bounds!) |
std::array<T, N> | Stack / Contiguous | Fixed at compile time | Yes (via .at(i)) |
std::string | Heap (Small String Opt) | Dynamic sizing | Yes (via .at(i)) |
std::string_view | Non-owning Pointer+Len | Fixed slice view | Yes |
std::vector<T> | Heap / Dynamic RAM | Resizable Dynamic Array | Yes (via .at(i)) |
#include <iostream>
#include <vector>
#include <string>
#include <string_view>
void printView(std::string_view sv) {
std::cout << "StringView: " << sv << " (length: " << sv.length() << ")\n";
}
int main() {
// std::vector Operations
std::vector<int> marks{85, 90, 78, 92};
marks.push_back(88);
marks.push_back(95);
std::cout << "Vector size: " << marks.size() << ", capacity: " << marks.capacity() << "\n";
std::cout << "Marks: ";
for (int m : marks) {
std::cout << m << " ";
}
std::cout << "\n";
// std::string & std::string_view
std::string text{"Modern C++ High-Performance Computing"};
std::string_view slice{text.c_str() + 7, 3}; // Zero-allocation view of "C++"
printView(slice);
return 0;
} Q1: What is the difference between vector size() and capacity()?
size() is the number of elements currently stored. capacity() is the total memory allocated before requiring reallocation.
Q2: Why use vector.reserve(n)?
Calling reserve(n) pre-allocates memory for n elements, avoiding repeated memory reallocation and element copying during push_back().
Q3: Why is std::string_view faster than const std::string&?
std::string_view does NOT allocate memory or copy string data โ it simply wraps a pointer and length, enabling zero-allocation substrings.
Q4: What is Small String Optimization (SSO)?
Most C++ compilers store short strings (up to 15-23 characters) directly inside the std::string object on the stack without heap allocation.
Q5: Difference between [] indexing and .at() method?
arr[i] does zero bounds checking for speed. arr.at(i) throws std::out_of_range exception if index is invalid.