Loading...

STL Reference

The Standard Template Library (STL) in C++ is a critical component of modern C++ development, providing a rich collection of generic classes and functions that simplify complex programming tasks. STL Reference in C++ serves as a comprehensive guide to understanding and using these components efficiently. It is essential for advanced C++ programmers who aim to write maintainable, high-performance, and scalable code. STL offers standardized data structures, including vectors, lists, sets, maps, and queues, alongside powerful algorithms for searching, sorting, and manipulating collections. Understanding STL Reference enables developers to leverage these tools to implement efficient solutions while adhering to object-oriented programming principles such as encapsulation, inheritance, and polymorphism. Using STL Reference in real-world C++ projects allows for rapid development without reinventing fundamental data structures or algorithms. In software architecture, STL facilitates modular, reusable, and optimized code, reducing memory footprint and improving runtime efficiency. In this reference, readers will explore STL syntax, container behaviors, iterator patterns, and algorithm usage. Additionally, it will highlight best practices, performance considerations, and integration strategies within large-scale C++ systems. By mastering STL Reference, developers gain the ability to write robust, error-resistant, and optimized C++ code, directly impacting software quality, maintainability, and performance in professional projects.

Basic Example

text
TEXT Code
\#include <iostream>
\#include <vector>
\#include <algorithm>

int main() {
std::vector<int> numbers = {10, 20, 30, 40, 50};

// Iterating over vector using range-based for loop
std::cout << "Original numbers: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;

// Using STL algorithm to reverse vector
std::reverse(numbers.begin(), numbers.end());

std::cout << "Reversed numbers: ";
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;

return 0;

}

The C++ code above demonstrates fundamental usage of the STL Reference, focusing on vectors and algorithms. We first include the necessary headers: for input/output, for the dynamic array container, and for built-in functions. A vector named 'numbers' is initialized with integers, showcasing the use of STL containers to manage data efficiently. The first loop uses a range-based for loop, an idiomatic C++11 feature, to traverse and print elements. This emphasizes safe iteration practices and avoids manual indexing errors. The std::reverse algorithm is applied to invert the vector elements, demonstrating STL’s capability to perform complex operations concisely without writing custom loops. The second loop uses an iterator, illustrating a key STL concept: iterators act as generalized pointers to traverse containers, ensuring compatibility across different data structures. This example also highlights best practices such as avoiding raw arrays, using auto for type deduction, and preventing memory leaks through automatic storage management of STL containers. In real-world C++ projects, such STL operations streamline data manipulation, enhance code readability, and minimize the risk of logical errors, aligning with advanced C++ development standards and system architecture principles.

Practical Example

text
TEXT Code
\#include <iostream>
\#include <map>
\#include <string>
\#include <algorithm>

class Student {
public:
std::string name;
int score;

Student(std::string n, int s) : name(n), score(s) {}

};

int main() {
std::map\<std::string, Student> studentRecords;
studentRecords\["A101"] = Student("Alice", 85);
studentRecords\["B202"] = Student("Bob", 92);
studentRecords\["C303"] = Student("Charlie", 78);

// Using STL algorithm to find student with max score
auto maxScoreIt = std::max_element(studentRecords.begin(), studentRecords.end(),
[](const auto& a, const auto& b) { return a.second.score < b.second.score; });

if (maxScoreIt != studentRecords.end()) {
std::cout << "Top student: " << maxScoreIt->second.name
<< " with score " << maxScoreIt->second.score << std::endl;
}

return 0;

}

Advanced C++ Implementation

text
TEXT Code
\#include <iostream>
\#include <vector>
\#include <set>
\#include <algorithm>
\#include <memory>

class Task {
public:
std::string description;
int priority;

Task(std::string d, int p) : description(d), priority(p) {}

};

int main() {
std::vector\<std::shared_ptr<Task>> tasks;
tasks.push_back(std::make_shared<Task>("Design Module", 2));
tasks.push_back(std::make_shared<Task>("Implement Feature", 1));
tasks.push_back(std::make_shared<Task>("Code Review", 3));

// Sorting tasks by priority using STL sort and lambda
std::sort(tasks.begin(), tasks.end(), [](const auto& a, const auto& b) {
return a->priority < b->priority;
});

std::cout << "Tasks sorted by priority: " << std::endl;
for (const auto& task : tasks) {
std::cout << task->description << " - Priority: " << task->priority << std::endl;
}

// Using STL set to store unique priorities
std::set<int> priorities;
for (const auto& task : tasks) {
priorities.insert(task->priority);
}

std::cout << "Unique priorities: ";
for (int p : priorities) {
std::cout << p << " ";
}
std::cout << std::endl;

return 0;

}

📊 Comprehensive Reference

C++ Element/Method Description Syntax Example Notes
vector Dynamic array container std::vector<Type> v; std::vector<int> v = {1,2,3}; Resizable array, fast index access
vector::push_back Add element at end v.push_back(value); v.push_back(4); Amortized O(1)
vector::size Returns number of elements v.size(); size_t n = v.size(); Constant time
vector::begin Iterator to first element v.begin(); auto it = v.begin(); Supports STL algorithms
vector::end Iterator past last element v.end(); auto it = v.end(); Used with algorithms
vector::erase Remove element at iterator v.erase(it); v.erase(v.begin()); Linear time for middle elements
vector::insert Insert element at iterator v.insert(it, value); v.insert(v.begin()+1, 10); Shifts elements, linear time
vector::clear Remove all elements v.clear(); v.clear(); Releases memory
vector::empty Check if container is empty v.empty(); if(v.empty()) ... Constant time
vector::front Access first element v.front(); int x = v.front(); Reference to first element
vector::back Access last element v.back(); int y = v.back(); Reference to last element
list Doubly-linked list std::list<Type> l; std::list<int> l = {1,2,3}; Efficient insert/erase anywhere
list::push_back Add element at end l.push_back(value); l.push_back(4); Constant time
list::push_front Add element at front l.push_front(value); l.push_front(0); Constant time
list::erase Remove element at iterator l.erase(it); l.erase(l.begin()); Constant time
list::insert Insert element at iterator l.insert(it, value); l.insert(l.begin(), 5); Constant time
list::size Return number of elements l.size(); size_t n = l.size(); Linear time for some implementations
deque Double-ended queue std::deque<Type> d; std::deque<int> d = {1,2,3}; Fast insertion/removal front/back
stack LIFO container adapter std::stack<Type> s; std::stack<int> s; Push/pop operations
stack::push Add element s.push(value); s.push(10); Adds to top
stack::pop Remove top element s.pop(); s.pop(); Undefined if empty
stack::top Access top element s.top(); int t = s.top(); Reference to top element
queue FIFO container adapter std::queue<Type> q; std::queue<int> q; Push back, pop front
queue::push Add element at end q.push(value); q.push(5); Enqueue operation
queue::pop Remove front element q.pop(); q.pop(); Dequeue operation
queue::front Access first element q.front(); int f = q.front(); Reference to front
queue::back Access last element q.back(); int b = q.back(); Reference to back
priority_queue Max-heap container std::priority_queue<Type> pq; std::priority_queue<int> pq; Default max-heap
priority_queue::push Add element pq.push(value); pq.push(20); Heap maintains order
priority_queue::pop Remove top element pq.pop(); pq.pop(); Removes max element
priority_queue::top Access top element pq.top(); int t = pq.top(); Reference to max element
set Unique sorted elements std::set<Type> s; std::set<int> s; Red-black tree, ordered
set::insert Add element s.insert(value); s.insert(10); Maintains order, O(log n)
set::erase Remove element s.erase(value); s.erase(10); O(log n)
set::find Search element s.find(value); auto it = s.find(5); Returns iterator or end()
unordered_set Hash-based unique elements std::unordered_set<Type> us; std::unordered_set<int> us; Average O(1) operations
map Key-value pairs, sorted std::map\<Key, Value> m; std::map\<int,std::string> m; Ordered associative container
map::insert Insert key-value m.insert({1,"A"}); m.insert({2,"B"}); Maintains order
map::erase Remove key m.erase(key); m.erase(1); O(log n)
map::find Search key m.find(key); auto it = m.find(2); Returns iterator
unordered_map Hash-based key-value std::unordered_map\<Key, Value> um; std::unordered_map\<int,std::string> um; Average O(1)
algorithm::sort Sort range std::sort(begin, end); std::sort(v.begin(), v.end()); Uses IntroSort
algorithm::reverse Reverse range std::reverse(begin, end); std::reverse(v.begin(), v.end()); In-place
algorithm::find Find element std::find(begin, end, value); auto it = std::find(v.begin(), v.end(), 3); Returns iterator or end
algorithm::max_element Find max element std::max_element(begin,end); auto it = std::max_element(v.begin(), v.end()); Returns iterator
algorithm::min_element Find min element std::min_element(begin,end); auto it = std::min_element(v.begin(), v.end()); Returns iterator
algorithm::accumulate Sum range std::accumulate(begin,end,0); int sum = std::accumulate(v.begin(),v.end(),0); Requires <numeric>
algorithm::count Count occurrences std::count(begin,end,value); int c = std::count(v.begin(),v.end(),5); Returns count
algorithm::binary_search Check sorted element std::binary_search(begin,end,value); bool exists = std::binary_search(v.begin(),v.end(),10); Requires sorted container
pair Tuple of two values std::pair\<Type1,Type2> p; std::pair\<int,std::string> p(1,"A"); Commonly used in maps
tuple Tuple of multiple values std::tuple\<Types...> t; std::tuple\<int,std::string,double> t(1,"A",2.5); C++11 onwards
iterator Access elements container.begin()/end(); auto it = v.begin(); Supports STL algorithms
reverse_iterator Reverse traversal container.rbegin()/rend(); auto rit = v.rbegin(); Reverse order iteration
emplace In-place construction v.emplace(pos,value); v.emplace(v.begin(),10); Efficient insertion
emplace_back In-place push_back v.emplace_back(value); v.emplace_back(20); Avoids copy/move
reserve Preallocate memory v.reserve(n); v.reserve(100); Reduces reallocations
capacity Current allocated size v.capacity(); size_t c = v.capacity(); May differ from size
shrink_to_fit Reduce capacity v.shrink_to_fit(); v.shrink_to_fit(); Non-binding request
array Fixed-size array std::array\<Type,N> a; std::array\<int,5> a = {1,2,3,4,5}; C++11 onwards
stack::empty Check if stack empty s.empty(); if(s.empty()) ... Constant time
queue::empty Check if queue empty q.empty(); if(q.empty()) ... Constant time
priority_queue::empty Check if heap empty pq.empty(); if(pq.empty()) ... Constant time
set::empty Check if set empty s.empty(); if(s.empty()) ... Constant time
map::empty Check if map empty m.empty(); if(m.empty()) ... Constant time
unordered_set::empty Check if unordered_set empty us.empty(); if(us.empty()) ... Constant time
unordered_map::empty Check if unordered_map empty um.empty(); if(um.empty()) ... Constant time
copy Copy range std::copy(begin,end,dest); std::copy(v.begin(),v.end(),out.begin()); Requires destination size
fill Fill range std::fill(begin,end,value); std::fill(v.begin(),v.end(),0); Sets all elements
replace Replace values std::replace(begin,end,old,new); std::replace(v.begin(),v.end(),2,5); In-place replacement
swap Swap containers std::swap(a,b); std::swap(v1,v2); Efficient element exchange
next_permutation Next lexicographical perm std::next_permutation(begin,end); std::next_permutation(v.begin(),v.end()); Requires sorted range
prev_permutation Previous permutation std::prev_permutation(begin,end); std::prev_permutation(v.begin(),v.end()); Reverse lex order

📊 Complete C++ Properties Reference

Property Values Default Description C++ Support
vector::capacity size_t 0 Current allocated storage C++98 onwards
vector::size size_t 0 Number of elements C++98 onwards
vector::empty bool true Whether container is empty C++98 onwards
map::key_type Type None Type of key C++98 onwards
map::mapped_type Type None Type of value C++98 onwards
set::key_type Type None Type of element C++98 onwards
deque::max_size size_t Implementation defined Maximum elements supported C++98 onwards
unordered_map::load_factor float 0 Average hash bucket load C++11 onwards
stack::size size_t 0 Number of elements C++98 onwards
priority_queue::size size_t 0 Number of elements C++98 onwards
array::size size_t 0 Fixed size of array C++11 onwards
tuple::size size_t Compile-time constant Number of elements C++11 onwards

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

3
Questions
🎯
70%
To Pass
♾️
Time
🔄
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top