C++ string and vector

The string class and vector template are two of the most important tools in the Standard C++ Library. Both hide low-level memory management so you can work at a higher level of abstraction.

std::string

Problem it solves

A C-style character array has fixed size at compile time. Appending, searching, or concatenating requires manual memory management — a constant source of bugs since the inception of C. The string class handles all of this for you.

#include <string>
using namespace std;

Basic Operations

string s1, s2;                 // empty strings
string s3 = "Hello, World.";   // initialize from character array
string s4("I am");             // alternate initialization syntax
 
s2 = "Today";                  // assign (replaces previous content automatically)
s1 = s3 + " " + s4;           // concatenate strings and/or character arrays
s1 += " 8";                    // append in place
 
cout << s1 + s2 + "!" << endl; // send string expression directly to cout
OperationMeaning
=Assign (replaces; old content freed automatically)
+Concatenate (strings or char arrays)
+=Append in place
<<Send to cout/ofstream

Dynamic Sizing

string grows automatically as you append. No need to know size in advance:

ifstream in("file.cpp");
string s, line;
while(getline(in, line))
    s += line + "\n";         // s expands with every iteration

std::vector (Template Container)

Problem it solves

When you don’t know how many objects you’ll need at runtime, a fixed array fails. vector is a dynamically-sized sequence container — it expands as you add elements.

Template Syntax

vector is a template: it can hold any type. Specify the type in angle brackets:

#include <vector>
vector<string>  lines;    // holds strings
vector<int>     numbers;  // holds ints
vector<float>   values;   // holds floats

The template generates a customized class for each type. You get a compile error if you try to push the wrong type.

Core Operations

vector<string> v;
 
// Add elements
v.push_back("a line");     // appends to the end
 
// Access elements (0-indexed, operator[] overloaded)
cout << v[2] << endl;      // third element
v[2] = "new value";        // assign to an element
 
// Size
v.size()                   // number of elements currently in the vector
MemberMeaning
push_back(x)Append x to end
v[i]Access element i (0-based)
v.size()Current number of elements

Loops with vector

while loop (reading until condition is false):

while(getline(in, line))        // true while a line was read
    v.push_back(line);

for loop (iterating over a vector):

for(int i = 0; i < v.size(); i++)
    cout << i << ": " << v[i] << endl;

The for control expression has three parts: init; test; increment

  • int i = 0 — initialize
  • i < v.size() — test (stay in loop while true)
  • i++ — auto-increment (i += 1 after each iteration)

Reading words instead of lines (>> splits on whitespace):

vector<string> words;
while(in >> word)
    words.push_back(word);

Complete File → Numbered Lines Example

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
 
int main() {
    vector<string> v;
    ifstream in("file.cpp");
    string line;
    while(getline(in, line))
        v.push_back(line);
    for(int i = 0; i < v.size(); i++)
        cout << i << ": " << v[i] << endl;
}

About the Standard Template Library (STL)

vector and the other containers come from the Standard Template Library designed by Alex Stepanov (at HP) and presented to the C++ Standards Committee in San Diego, 1994. The committee integrated it into the Standard C++ Library with modifications. The SGI STL continues to diverge — this book uses “Standard C++ Library containers,” not “STL.”

graph TD
    A[Standard C++ Library] --> B[string class]
    A --> C[vector template]
    A --> D[Other containers]
    B --> E[Dynamic string storage]
    B --> F[+ concatenation]
    B --> G[+= append]
    C --> H["vector&lt;T&gt;: holds any type"]
    H --> I[push_back: add to end]
    H --> J["[i]: indexed access"]
    H --> K[size: element count]
    C --> L[Template: compiler generates\ncustomized class per type]

Key Points

  • string and vector are in namespace std; always #include <string> or #include <vector> explicitly
  • string = replaces content entirely (memory management handled internally)
  • vector[i] uses operator overloading — works like an array but bounds are managed
  • push_back is named specifically because insert (add to middle) also exists; push_front does not exist on vector
  • v.size() returns an unsigned integer type; compare with int via explicit cast or use size_t
  • i++ = post-increment (returns old value, then increments); in a for loop they’re equivalent
  • The while(getline(in, s)) idiom is idiomatic C++ for “read file line by line”