← Back to C++ Course | Chapter 13: STL Containers & Algorithms | Lesson 1 of 15

C++ STL Introduction

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?

cpp
#include <iostream>
#include <vector>

int main() {
	std::vector<int> nums = {3, 1, 2};
	std::cout << nums[0] << std::endl;
	return 0;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.