🟢 C++ Language — Headers, Namespaces & Code Examples

Complete reference for the C++ Standard Library — headers, the std namespace, key functions, and ready-to-compile programs. Designed for students and developers.
Part of The Direct Path to Linux Ubuntu — free for all students.

12Headers
180+Symbols
4Namespaces
5Examples
g++Compiler
C++17Standard
HTTPSPort 443
📺 Input / Output 🔤 Strings 📦 Containers 🔄 Algorithms 🧠 Memory Management ⚠️ Error Handling 🧵 Concurrency 🏷 Namespaces ⚡ Examples

📺 Input / Output

📺 <iostream>Standard Input / Output Streams
📁 <fstream>File I/O Streams
🌊 <sstream>String Streams — In-Memory I/O

🔤 Strings

🔤 <string>std::string — Dynamic String Class

📦 Containers

📦 <vector>std::vector — Dynamic Array Container
🗺️ <map>std::map & std::unordered_map — Associative Containers

🔄 Algorithms

🔄 <algorithm>Standard Algorithms — Sort, Search, Transform
λ <functional>Lambdas, std::function, std::bind

🧠 Memory Management

🧠 <memory>Smart Pointers — unique_ptr, shared_ptr, weak_ptr

⚠️ Error Handling

⚠️ <stdexcept>Standard Exception Classes
❓ <optional>std::optional — Nullable Values (C++17)

🧵 Concurrency

🧵 <thread>std::thread — Multi-threading (C++11)

🏷 Namespaces Quick Reference

NamespaceDescriptionKey Symbols
stdThe entire C++ Standard Library lives here. Use using namespace std; in examples, or qualify each name as std::cout in production code.cout, cin, cerr, clog, endl, getline
string, to_string, stoi, stol, stod
vector, map, unordered_map, set, queue, stack, deque, list
sort, find, for_each, transform, count_if, accumulate
unique_ptr, shared_ptr, weak_ptr, make_unique, make_shared
thread, mutex, lock_guard, condition_variable, atomic
function, bind, invoke, placeholders::_1
optional, variant, any, tuple, pair
exception, runtime_error, logic_error, bad_alloc
ifstream, ofstream, fstream, istringstream, ostringstream
std::chronoSub-namespace for time and duration types (C++11). Include <chrono>.hours, minutes, seconds, milliseconds, microseconds, nanoseconds
duration, time_point
system_clock, steady_clock, high_resolution_clock
duration_cast&lt;T&gt;
std::literalsUser-defined literal suffixes (C++14). Activate with using namespace std::literals;."hello"s &rarr; std::string
1s, 2ms, 500us &rarr; std::chrono durations
std::filesystemFile system operations (C++17). Include <filesystem>. Link with -lstdc++fs on older GCC.path, directory_entry, directory_iterator
exists, is_regular_file, is_directory
create_directory, remove, rename, copy
file_size, last_write_time

⚡ Quick Copy-Paste Examples

Save any file as .cpp and compile with the command shown in the last comment. All examples target -std=c++17.

Hello, C++ World!

Classic first program — output to cout.

#include <iostream>
using namespace std;
int main() {
    cout << "Hello, C++ World!" << endl;
    return 0;
}
// g++ -Wall -std=c++17 -o hello hello.cpp && ./hello

Classes & OOP

Define a class with constructor and member functions.

#include <iostream>
#include <string>
using namespace std;

class Rectangle {
    double width, height;
public:
    Rectangle(double w, double h) : width(w), height(h) {}
    double area()      const { return width * height; }
    double perimeter() const { return 2 * (width + height); }
    string describe()  const {
        return to_string(width) + " x " + to_string(height);
    }
};

int main() {
    Rectangle r(5.0, 3.0);
    cout << "Shape    : " << r.describe()  << "\n";
    cout << "Area     : " << r.area()      << "\n";
    cout << "Perimeter: " << r.perimeter() << "\n";
    return 0;
}
// g++ -Wall -std=c++17 -o rect rect.cpp

Templates

Generic functions and a simple generic Stack class.

#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;

template<typename T>
T maximum(T a, T b) { return (a > b) ? a : b; }

template<typename T>
class Stack {
    vector<T> data;
public:
    void push(const T &x) { data.push_back(x); }
    void pop()  { if (data.empty()) throw underflow_error("empty"); data.pop_back(); }
    T &  top()  { if (data.empty()) throw underflow_error("empty"); return data.back(); }
    bool empty() const { return data.empty(); }
};

int main() {
    cout << maximum(3, 7) << "\n";
    cout << maximum(string("apple"), string("banana")) << "\n";

    Stack<int> s;
    s.push(10); s.push(20); s.push(30);
    while (!s.empty()) { cout << s.top() << " "; s.pop(); }
    cout << "\n";
    return 0;
}
// g++ -Wall -std=c++17 -o templates templates.cpp

Inheritance & Polymorphism

Virtual functions, override, and dynamic dispatch.

#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class Shape {
public:
    virtual double area() const = 0;
    virtual string name() const = 0;
    virtual ~Shape() = default;
};

class Circle : public Shape {
    double r;
public:
    Circle(double r) : r(r) {}
    double area() const override { return 3.14159 * r * r; }
    string name() const override { return "Circle"; }
};

class Rect : public Shape {
    double w, h;
public:
    Rect(double w, double h) : w(w), h(h) {}
    double area() const override { return w * h; }
    string name() const override { return "Rectangle"; }
};

int main() {
    vector<unique_ptr<Shape>> shapes;
    shapes.push_back(make_unique<Circle>(5.0));
    shapes.push_back(make_unique<Rect>(4.0, 6.0));
    shapes.push_back(make_unique<Circle>(2.5));
    for (const auto &s : shapes)
        cout << s->name() << " area = " << s->area() << "\n";
    return 0;
}
// g++ -Wall -std=c++17 -o poly poly.cpp

Lambdas & Algorithms

Use lambdas with STL algorithms for clean, expressive code.

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <string>
using namespace std;

int main() {
    vector<int> v = {1,2,3,4,5,6,7,8,9,10};

    vector<int> evens;
    copy_if(v.begin(), v.end(), back_inserter(evens),
            [](int x){ return x % 2 == 0; });
    cout << "Evens: ";
    for (int x : evens) cout << x << " ";
    cout << "\n";

    int sum_sq = accumulate(v.begin(), v.end(), 0,
                            [](int acc, int x){ return acc + x * x; });
    cout << "Sum of squares: " << sum_sq << "\n";

    vector<string> words = {"banana","fig","apple","kiwi","cherry"};
    sort(words.begin(), words.end(),
         [](const string &a, const string &b){ return a.size() < b.size(); });
    cout << "By length: ";
    for (auto &w : words) cout << w << " ";
    cout << "\n";
    return 0;
}
// g++ -Wall -std=c++17 -o lambdas lambdas.cpp