Vectors_strings
Vectors and Strings
Section titled “Vectors and Strings”Vectors and strings are among the most commonly used STL containers. This chapter covers them in detail with practical examples.
std::vector
Section titled “std::vector”std::vector is a dynamic array that can grow and shrink automatically. It’s the most commonly used container in C++.
Creating Vectors
Section titled “Creating Vectors”#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));}Accessing Elements
Section titled “Accessing Elements”std::vector<int> vec = {10, 20, 30, 40, 50};
// Index-based accessint first = vec[0]; // 10 (no bounds checking)int third = vec.at(2); // 30 (with bounds checking)
// First and lastint front = vec.front(); // 10int back = vec.back(); // 50
// Data pointer (for C interop)int* ptr = vec.data();Modifying Vectors
Section titled “Modifying Vectors”std::vector<int> vec = {1, 2, 3};
// Add elementsvec.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 elementsvec.pop_back(); // {1, 2, 99, 3, 4}vec.erase(vec.begin() + 2); // {1, 2, 3, 4}
// Clear allvec.clear(); // empty
// Resizevec.resize(10); // 10 elements (default 0)vec.resize(5, 42); // Resize to 5, fill with 42Capacity Management
Section titled “Capacity Management”std::vector<int> vec;
// Check capacityvec.size(); // Number of elementsvec.capacity(); // Allocated spacevec.empty(); // true if empty
// Reserve space (avoid reallocations)vec.reserve(1000); // Pre-allocate for 1000 elementsvec.shrink_to_fit(); // Release extra capacityIterating Over Vectors
Section titled “Iterating Over Vectors”std::vector<int> vec = {1, 2, 3, 4, 5};
// Range-based for loop (C++11)for (int val : vec) { std::cout << val << " ";}
// With indexfor (size_t i = 0; i < vec.size(); i++) { std::cout << vec[i] << " ";}
// Using iteratorsfor (auto it = vec.begin(); it != vec.end(); ++it) { std::cout << *it << " ";}
// Modern C++ (auto)for (const auto& val : vec) { std::cout << val << " ";}std::string
Section titled “std::string”std::string is a container for character strings with many useful methods.
Creating Strings
Section titled “Creating Strings”#include <string>
std::string s1; // Empty stringstd::string s2 = "Hello"; // From C-stringstd::string s3("World"); // Constructorstd::string s4(5, 'x'); // "xxxxx"std::string s5 = s2; // Copystd::string s6 = std::move(s5); // MoveString Operations
Section titled “String Operations”std::string s = "Hello, World!";
// Accesschar c = s[0]; // 'H'char c2 = s.at(1); // 'e'
// Sizesize_t len = s.length(); // 13size_t len2 = s.size(); // Same
// Concatenationstd::string a = "Hello";std::string b = "World";std::string c = a + ", " + b + "!"; // "Hello, World!"
// Appenda.append(" World");
// Findsize_t pos = s.find("World"); // 7size_t pos2 = s.find('o'); // 4size_t notFound = s.find('z'); // std::string::npos
// Substringstd::string sub = s.substr(0, 5); // "Hello"std::string sub2 = s.substr(7); // "World!"
// Replaces.replace(0, 5, "Hi"); // "Hi, World!"String Modifiers
Section titled “String Modifiers”std::string s = " Hello ";
s += " World"; // Appends.insert(0, ">>"); // Insert at positions.erase(0, 2); // Erase characterss.clear(); // Empty the string
// Trim whitespaces.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);String Conversions
Section titled “String Conversions”#include <string>
// Number to stringstd::string s1 = std::to_string(42);std::string s2 = std::to_string(3.14);
// String to numberint i = std::stoi("42");double d = std::stod("3.14");long l = std::stol("123456");
// String view (C++17) - no copystd::string_view sv = "Hello"; // Lightweight referenceComplete Example: Word Counter
Section titled “Complete Example: Word Counter”#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;}Vector of Custom Objects
Section titled “Vector of Custom Objects”#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;}Best Practices
Section titled “Best Practices”Vector Best Practices
Section titled “Vector Best Practices”- Use
reserve()when you know the size
std::vector<int> vec;vec.reserve(1000); // Avoid reallocations- Use
emplace_back()instead ofpush_back()
vec.emplace_back(42); // Construct in place, no copy- Prefer range-based for loops
for (const auto& item : vec) { // const ref avoids copy // Use item}String Best Practices
Section titled “String Best Practices”- Use
std::string_viewfor read-only strings (C++17)
void process(std::string_view sv); // Accepts both string and char*- Use
std::to_stringfor conversions
std::string s = std::to_string(42);- Avoid C-style strings - use
std::string
Key Takeaways
Section titled “Key Takeaways”std::vectoris the default container for sequential data- Use
push_back()oremplace_back()to add elements - Use
reserve()to pre-allocate memory std::stringprovides powerful string manipulation- Use
std::string_view(C++17) for non-owning string references - Prefer range-based for loops over index-based iteration
Next Steps
Section titled “Next Steps”Let’s learn about maps and sets.
Next Chapter: 16_maps_sets.md - Maps and Sets