C++ STL Introduction
In this page:
What is the STL?
The Standard Template Library (STL) is a large set of template classes and functions built into C++ that provides pre-written, highly optimized data structures and algorithms, sparing you from writing basic utilities like sorting or dynamic arrays from scratch.
Example: What is the STL?
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {3, 1, 2};
std::cout << nums[0] << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Containers Overview
Containers are template classes designed to store and manage collections of data, split broadly into sequence containers like vector and deque, which preserve insertion order, and associative containers like set and map, which organize elements by key.
Example: Containers Overview
#include <iostream>
#include <vector>
#include <map>
#include <string>
int main() {
std::vector<int> sequence = {1, 2, 3};
std::map<std::string, int> lookup = {{"a", 1}};
std::cout << sequence[0] << " " << lookup["a"] << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
STL Algorithms Intro
STL algorithms are free template functions — not member functions of the containers — that operate on ranges of elements to find, sort, copy, or search, which means the same algorithm works uniformly across many different container types.
Example: STL Algorithms Intro
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {3, 1, 2};
std::sort(nums.begin(), nums.end());
std::cout << nums[0] << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
STL Iterators
Iterators are smart-pointer-like objects used to walk through the elements of a container one at a time, giving every container type — no matter how differently it's implemented internally — a consistent, uniform way to be traversed by algorithms.
Example: STL Iterators
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3};
for (auto it = nums.begin(); it != nums.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Benefits of the STL
Relying on the STL instead of hand-rolled utilities improves both productivity and reliability: because it's written and maintained by compiler and library specialists, its containers and algorithms are extensively tested, memory-safe, and highly optimized.
Example: Benefits of the STL
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {5, 3, 1, 4};
std::sort(nums.begin(), nums.end());
for (int n : nums) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: