Skip to content

Vectors_strings

Vectors and strings are among the most commonly used STL containers. This chapter covers them in detail with practical examples.

std::vector is a dynamic array that can grow and shrink automatically. It’s the most commonly used container in C++.

#include <vector>
#include <iostream>
int main() {
// Empty vector
std::vector<int> emptyVec;
// Vector with size
std::vector<int> sizedVec(5); // 5 elements, all 0
// Vector with size and initial value
std::vector<int> initializedVec(5, 10); // 5 elements, all 10
// Initialize from list (C++11)
std::vector<int> listVec = {1, 2, 3, 4, 5};
// Copy and move constructors
std::vector<int> copyVec(listVec);
std::vector<int> moveVec(std::move(listVec));
}
std::vector<int> vec = {10, 20, 30, 40, 50};
// Index-based access
int first = vec[0]; // 10 (no bounds checking)
int third = vec.at(2); // 30 (with bounds checking)
// First and last
int front = vec.front(); // 10
int back = vec.back(); // 50
// Data pointer (for C interop)
int* ptr = vec.data();
std::vector<int> vec = {1, 2, 3};
// Add elements
vec.push_back(4); // {1, 2, 3, 4}
vec.push_back(5); // {1, 2, 3, 4, 5}
// Insert (expensive - shifts elements)
vec.insert(vec.begin() + 2, 99); // {1, 2, 99, 3, 4, 5}
// Remove elements
vec.pop_back(); // {1, 2, 99, 3, 4}
vec.erase(vec.begin() + 2); // {1, 2, 3, 4}
// Clear all
vec.clear(); // empty
// Resize
vec.resize(10); // 10 elements (default 0)
vec.resize(5, 42); // Resize to 5, fill with 42
std::vector<int> vec;
// Check capacity
vec.size(); // Number of elements
vec.capacity(); // Allocated space
vec.empty(); // true if empty
// Reserve space (avoid reallocations)
vec.reserve(1000); // Pre-allocate for 1000 elements
vec.shrink_to_fit(); // Release extra capacity
std::vector<int> vec = {1, 2, 3, 4, 5};
// Range-based for loop (C++11)
for (int val : vec) {
std::cout << val << " ";
}
// With index
for (size_t i = 0; i < vec.size(); i++) {
std::cout << vec[i] << " ";
}
// Using iterators
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
// Modern C++ (auto)
for (const auto& val : vec) {
std::cout << val << " ";
}

std::string is a container for character strings with many useful methods.

#include <string>
std::string s1; // Empty string
std::string s2 = "Hello"; // From C-string
std::string s3("World"); // Constructor
std::string s4(5, 'x'); // "xxxxx"
std::string s5 = s2; // Copy
std::string s6 = std::move(s5); // Move
std::string s = "Hello, World!";
// Access
char c = s[0]; // 'H'
char c2 = s.at(1); // 'e'
// Size
size_t len = s.length(); // 13
size_t len2 = s.size(); // Same
// Concatenation
std::string a = "Hello";
std::string b = "World";
std::string c = a + ", " + b + "!"; // "Hello, World!"
// Append
a.append(" World");
// Find
size_t pos = s.find("World"); // 7
size_t pos2 = s.find('o'); // 4
size_t notFound = s.find('z'); // std::string::npos
// Substring
std::string sub = s.substr(0, 5); // "Hello"
std::string sub2 = s.substr(7); // "World!"
// Replace
s.replace(0, 5, "Hi"); // "Hi, World!"
std::string s = " Hello ";
s += " World"; // Append
s.insert(0, ">>"); // Insert at position
s.erase(0, 2); // Erase characters
s.clear(); // Empty the string
// Trim whitespace
s.erase(0, s.find_first_not_of(' '));
s.erase(s.find_last_not_of(' ') + 1);
// To upper/lower (C++20 has std::tolower/toupper)
#include <cctype>
for (char& c : s) c = std::toupper(c);
#include <string>
// Number to string
std::string s1 = std::to_string(42);
std::string s2 = std::to_string(3.14);
// String to number
int i = std::stoi("42");
double d = std::stod("3.14");
long l = std::stol("123456");
// String view (C++17) - no copy
std::string_view sv = "Hello"; // Lightweight reference
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
int main() {
std::string text = "The quick brown fox jumps over the lazy dog "
"and the fox is very quick";
// Split into words
std::vector<std::string> words;
std::stringstream ss(text);
std::string word;
while (ss >> word) {
// Convert to lowercase
for (char& c : word) {
c = std::tolower(c);
}
words.push_back(word);
}
// Display unique words
std::cout << "All words:\n";
for (const auto& w : words) {
std::cout << w << "\n";
}
// Sort
std::sort(words.begin(), words.end());
// Count occurrences
std::cout << "\nWord frequencies:\n";
for (size_t i = 0; i < words.size(); ) {
size_t count = 0;
std::string current = words[i];
while (i < words.size() && words[i] == current) {
count++;
i++;
}
std::cout << current << ": " << count << "\n";
}
// Find "fox"
auto it = std::find(words.begin(), words.end(), "fox");
if (it != words.end()) {
std::cout << "\n'fox' found at position "
<< (it - words.begin()) + 1 << "\n";
}
return 0;
}
#include <vector>
#include <iostream>
#include <string>
class Person {
private:
std::string name;
int age;
public:
Person(const std::string& n, int a) : name(n), age(a) {}
// For sorting
bool operator<(const Person& other) const {
return age < other.age;
}
void display() const {
std::cout << name << ", " << age << " years old\n";
}
};
int main() {
std::vector<Person> people = {
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35}
};
// Sort by age
std::sort(people.begin(), people.end());
// Display
for (const auto& p : people) {
p.display();
}
return 0;
}
  1. Use reserve() when you know the size
std::vector<int> vec;
vec.reserve(1000); // Avoid reallocations
  1. Use emplace_back() instead of push_back()
vec.emplace_back(42); // Construct in place, no copy
  1. Prefer range-based for loops
for (const auto& item : vec) { // const ref avoids copy
// Use item
}
  1. Use std::string_view for read-only strings (C++17)
void process(std::string_view sv); // Accepts both string and char*
  1. Use std::to_string for conversions
std::string s = std::to_string(42);
  1. Avoid C-style strings - use std::string
  • std::vector is the default container for sequential data
  • Use push_back() or emplace_back() to add elements
  • Use reserve() to pre-allocate memory
  • std::string provides powerful string manipulation
  • Use std::string_view (C++17) for non-owning string references
  • Prefer range-based for loops over index-based iteration

Let’s learn about maps and sets.

Next Chapter: 16_maps_sets.md - Maps and Sets