Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Comprehensive Guide to C++ Standard Template Library Containers

Tools May 8 3

Vector Dynamic Array Container

Initialization

std::vector<int> numericVector;
std::vector<double> floatingVector;
std::vector<int> sizedVector(10); // 10 elements initialized to 0
std::vector<int> filledVector(10, 5); // 10 elements initialized to 5
std::vector<std::vector<int>> matrix2D;
std::vector<int> fixedRows[5]; // 5 rows with variable columns
std::vector<std::vector<int>> initializedMatrix(3, std::vector<int>(4, 0)); // 3x4 matrix filled with 0

Member Functions

v.front()Returns first element
v.back()Returns last element
v.pop_back()Removes last element
v.push_back(val)Adds element to end
v.size()Returns element count
v.clear()Removes all elements
v.resize(n, val)Resizes with optional fill value
v.insert(it, val)Inserts at iterator position
v.erase(first, last)Removes range of elements
v.begin()Iterator to first element
v.end()Iterator past last element
v.empty()Checks if empty
std::sort(v.begin(), v.end())Sorts ascending
std::vector<int> dataVec;

for (int i = 0; i < 10; ++i) {
    dataVec.push_back(i);
}

std::cout << "First: " << dataVec.front() << std::endl;
std::cout << "Last: " << dataVec.back() << std::endl;

dataVec.pop_back();
std::cout << "Size: " << dataVec.size() << std::endl;

dataVec.clear();
dataVec.resize(5, 9);

dataVec.insert(dataVec.begin() + 2, 7);
dataVec.erase(dataVec.begin(), dataVec.begin() + 3);

if (dataVec.empty()) std::cout << "Empty" << std::endl;
std::sort(dataVec.begin(), dataVec.end());

Element Access

// Index-based access
for (size_t idx = 0; idx < dataVec.size(); ++idx) {
    std::cout << dataVec[idx] << " ";
}
// Iterator-based access
for (auto it = dataVec.begin(); it != dataVec.end(); ++it) {
    std::cout << *it << " ";
}

// Range-based loop (C++11+)
for (const auto& elem : dataVec) {
    std::cout << elem << " ";
}

Stack Container Adapter

Initialization

std::stack<int> intStack;
std::stack<double> doubleStack;

Member Functions

s.push(val)Adds element to top
s.top()Accesses top element
s.size()Returns element count
s.pop()Removes top element
s.empty()Checks if empty
std::stack<int> calculationStack;

calculationStack.push(42);
calculationStack.push(17);

std::cout << "Top: " << calculationStack.top() << std::endl;
std::cout << "Count: " << calculationStack.size() << std::endl;

calculationStack.pop();

if (calculationStack.empty()) std::cout << "Stack is empty" << std::endl;

Queue Container Adapter

Initialization

std::queue<int> processQueue;
std::queue<std::string> messageQueue;

Member Functions

q.push(val)Adds to back
q.front()Accesses front element
q.back()Accesses back element
q.size()Returns element count
q.empty()Checks if empty
q.pop()Removes front element
std::queue<int> taskQueue;

taskQueue.push(101);
taskQueue.push(202);
taskQueue.push(303);

std::cout << "Front: " << taskQueue.front() << std::endl;
std::cout << "Back: " << taskQueue.back() << std::endl;
std::cout << "Size: " << taskQueue.size() << std::endl;

taskQueue.pop();

if (taskQueue.empty()) std::cout << "Queue is empty" << std::endl;

Double-Ended Queue Container

Initialization

std::deque<int> buffer;
std::deque<char> characterBuffer;

Member Functions

dq.push_back(val)Adds to back
dq.push_front(val)Adds to front
dq.back()Accesses back element
dq.front()Accesses front element
dq.pop_back()Removes back element
dq.pop_front()Removes front element
dq.erase(it)Removes element at iterator
dq.erase(first, last)Removes range of elements
dq.empty()Checks if empty
dq.size()Returns element count
dq.clear()Removes all elements
std::deque<int> slidingWindow;

slidingWindow.push_front(5);
slidingWindow.push_back(10);
slidingWindow.push_front(3);

std::cout << "Front: " << slidingWindow.front() << std::endl;
std::cout << "Back: " << slidingWindow.back() << std::endl;

slidingWindow.pop_front();
slidingWindow.pop_back();

slidingWindow.erase(slidingWindow.begin() + 1);
slidingWindow.erase(slidingWindow.begin(), slidingWindow.end());

if (slidingWindow.empty()) std::cout << "Deque is empty" << std::endl;
std::cout << "Size: " << slidingWindow.size() << std::endl;

slidingWindow.clear();

Priority Queue Container Adapter

Initialization

std::priority_queue<int> defaultHeap;
std::priority_queue<double> floatingHeap;

Member Functions

pq.push(val)Inserts element
pq.top()Accesses highest priority
pq.size()Returns element count
pq.empty()Checks if empty
pq.pop()Removes highest priority
std::priority_queue<int> taskHeap;

taskHeap.push(5);
taskHeap.push(3);
taskHeap.push(8);

std::cout << "Top: " << taskHeap.top() << std::endl;
std::cout << "Size: " << taskHeap.size() << std::endl;

if (taskHeap.empty()) std::cout << "Heap is empty" << std::endl;

taskHeap.pop();

Priority Configuration

Basic Types

std::priority_queue<int> maxHeap; // Default: largest element first
std::priority_queue<int, std::vector<int>, std::less<int>> maxHeapExplicit;
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap; // Smallest first

Custom Structures

struct Task {
    int priority;
    int id;
    bool operator<(const Task& other) const {
        return priority < other.priority;
    }
};

std::priority_queue<Task> taskQueue;

Pair Storage

std::priority_queue<std::pair<int, int>> pairHeap;

pairHeap.push({10, 20});
pairHeap.push({10, 30});
pairHeap.push({20, 30});

while (!pairHeap.empty()) {
    auto top = pairHeap.top();
    std::cout << top.first << ", " << top.second << std::endl;
    pairHeap.pop();
}

Map Associative Container

Initialization

std::map<std::string, int> scores;
std::map<int, std::string> names;
std::map<std::string, std::string> dictionary;

Member Functions

m.find(key)Returns iterator to key or end()
m.erase(it)Removes element at iterator
m.erase(key)Removes element by key
m.erase(first, last)Removes range of elements
m.size()Returns element count
m.clear()Removes all elements
m.insert({key, val})Inserts key-value pair
m.empty()Checks if empty
m.begin()Iterator to first element
m.end()Iterator past last element
m.rbegin()Reverse iterator to last
m.rend()Reverse iterator before first
m.count(key)Returns 1 if key exists
m.lower_bound(key)Iterator to first element >= key
m.upper_bound(key)Iterator to first element > key
std::map<int, std::string> studentMap;

studentMap[101] = "Alice";
studentMap[102] = "Bob";
studentMap[103] = "Charlie";

auto it = studentMap.find(102);
if (it != studentMap.end()) {
    std::cout << "Found: " << it->first << " = " << it->second << std::endl;
}

studentMap.erase(studentMap.begin());
studentMap.erase(103);

std::cout << "Size: " << studentMap.size() << std::endl;

studentMap.clear();
studentMap.insert({201, "David"});

if (studentMap.empty()) std::cout << "Map is empty" << std::endl;
std::cout << "Count for key 201: " << studentMap.count(201) << std::endl;

// Traversal
for (const auto& [key, value] : studentMap) {
    std::cout << key << ": " << value << std::endl;
}

// Bounds checking
auto lower = studentMap.lower_bound(200);
auto upper = studentMap.upper_bound(200);

if (lower != studentMap.end()) 
    std::cout << "Lower bound: " << lower->first << std::endl;
if (upper != studentMap.end()) 
    std::cout << "Upper bound: " << upper->first << std::endl;

Element Access

std::map<int, std::string> config;
config[1] = "enabled";
config[2] = "disabled";

// Subscript access
std::cout << "Config 1: " << config[1] << std::endl;

// Iterator access
for (auto it = config.begin(); it != config.end(); ++it) {
    std::cout << it->first << " = " << it->second << std::endl;
}

// Find and access
auto found = config.find(2);
if (found != config.end()) {
    std::cout << "Found: " << found->second << std::endl;
}

Set Associative Container

Initialization

std::set<int> integerSet;
std::set<std::string> stringSet;

Member Functions

s.begin()Iterator to first element
s.end()Iterator past last element
s.rbegin()Reverse iterator to last
s.rend()Reverse iterator before first
s.clear()Removes all elements
s.empty()Checks if empty
s.insert(val)Inserts element
s.size()Returns element count
s.erase(it)Removes element at iterator
s.erase(first, last)Removes range of elements
s.erase(val)Removes specific value
s.find(val)Finds element or returns end()
s.count(val)Returns 1 if element exists
s.lower_bound(val)Iterator to first >= val
s.upper_bound(val)Iterator to first > val
std::set<int> uniqueNumbers;

uniqueNumbers.clear();
if (uniqueNumbers.empty()) std::cout << "Set is empty" << std::endl;

uniqueNumbers.insert(5);
uniqueNumbers.insert(3);
uniqueNumbers.insert(7);
uniqueNumbers.insert(3); // Duplicate ignored

std::cout << "Size: " << uniqueNumbers.size() << std::endl;

uniqueNumbers.erase(uniqueNumbers.begin());
uniqueNumbers.erase(5);

auto search = uniqueNumbers.find(7);
if (search != uniqueNumbers.end()) {
    std::cout << "Found 7" << std::endl;
}

std::cout << "Count of 3: " << uniqueNumbers.count(3) << std::endl;

auto lower = uniqueNumbers.lower_bound(4);
auto upper = uniqueNumbers.upper_bound(6);

if (lower != uniqueNumbers.end()) 
    std::cout << "Lower bound: " << *lower << std::endl;
if (upper != uniqueNumbers.end()) 
    std::cout << "Upper bound: " << *upper << std::endl;

Element Access

std::set<int> numberSet = {10, 20, 30, 40, 50};

// Iterator access
for (auto it = numberSet.begin(); it != numberSet.end(); ++it) {
    std::cout << *it << " ";
}
std::cout << std::endl;

// Access last element
if (!numberSet.empty()) {
    std::cout << "Last: " << *numberSet.rbegin() << std::endl;
    std::cout << "Last via end: " << *std::prev(numberSet.end()) << std::endl;
}

Custom Comparison

Basic Types

std::set<int> ascendingSet; // Default ascending
std::set<int, std::greater<int>> descendingSet;

Custom Structures

struct Point {
    int x, y;
    bool operator<(const Point& other) const {
        if (x != other.x) return x < other.x;
        return y < other.y;
    }
};

std::set<Point> pointSet;
pointSet.insert({1, 2});
pointSet.insert({3, 4});
pointSet.insert({1, 1});

for (const auto& p : pointSet) {
    std::cout << "(" << p.x << ", " << p.y << ") ";
}

Pair Utility Structure

Initialization

std::pair<std::string, int> defaultPair;
std::pair<std::string, int> initializedPair("answer", 42);
std::pair<int, double> anotherPair = std::make_pair(7, 3.14);
std::pair<char, bool> constructedPair('x', true);

Element Access

std::pair<int, int> coordinates[3];

coordinates[0] = {10, 20};
coordinates[1] = std::make_pair(30, 40);
coordinates[2] = std::pair<int, int>(50, 60);

for (int i = 0; i < 3; ++i) {
    std::cout << "Point " << i << ": (" 
              << coordinates[i].first << ", " 
              << coordinates[i].second << ")" << std::endl;
}

String Class

Initialization

std::string emptyStr;
std::string literalStr("Hello World");
std::string substring("Hello World", 0, 5); // "Hello"
std::string sizedStr(8, 'x'); // "xxxxxxxx"
std::string copyStr(literalStr, 6); // "World"

Element Access

std::string text = "Programming";

for (size_t i = 0; i < text.size(); ++i) {
    std::cout << text[i] << " ";
}
std::cout << std::endl;

// Array of strings
std::string words[3] = {"C++", "STL", "Containers"};
for (int i = 0; i < 3; ++i) {
    std::cout << i << ": " << words[i] << std::endl;
}

Input Operations

std::string input1, input2;
int number;

std::cin >> input1; // Reads until whitespace
std::cin.ignore(); // Clear buffer
std::getline(std::cin, input2); // Reads entire line

std::cin >> number;
std::cin.get(); // Consume newline
std::getline(std::cin, input1); // Read next line

Member Functions

s.size(), s.length()Character count
s.push_back(c)Adds character to end
s.insert(pos, val)Inserts at position
s.append(str)Concatenates string
s.erase(pos, n)Removes n characters from pos
s.erase(it)Removes character at iterator
s.erase(first, last)Removes range
s.clear()Removes all characters
s.replace(pos, n, str)Replaces substring
s.substr(pos, n)Returns substring
s.find(str, pos)Finds substring
s.find(c, pos)Finds character
std::sort(s.begin(), s.end())Sorts characters
std::string text("Hello");

std::cout << "Size: " << text.size() << std::endl;

text.push_back('!');
std::cout << text << std::endl;

text.insert(5, " World");
std::cout << text << std::endl;

text.append(" 2023");
std::cout << text << std::endl;

text.erase(5, 6);
std::cout << text << std::endl;

text.replace(0, 5, "Hi");
std::cout << text << std::endl;

std::string sub = text.substr(0, 2);
std::cout << "Substring: " << sub << std::endl;

if (text.find("Hi") != std::string::npos) {
    std::cout << "Found 'Hi'" << std::endl;
}

std::sort(text.begin(), text.end());
std::cout << "Sorted: " << text << std::endl;

text.clear();

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.