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

C++ Iterators

Introduction to Iterators

Iterators are objects that behave like generalized pointers into a container's elements, giving you a uniform way to step through and access elements sequentially regardless of how that particular container is implemented internally.

Example: Introduction to Iterators

cpp
#include <iostream>
#include <vector>

int main() {
	std::vector<int> nums = {1, 2, 3};
	std::vector<int>::iterator it = nums.begin();
	std::cout << *it << std::endl;
	return 0;
}

Reverse Iterators

Reverse iterators let you traverse a container from its last element back to its first; incrementing a reverse iterator actually moves it backward through the underlying container, which is exactly the behavior algorithms like std::sort(rbegin(), rend()) rely on.

Example: Reverse Iterators

cpp
#include <iostream>
#include <vector>

int main() {
	std::vector<int> nums = {1, 2, 3};
	for (auto it = nums.rbegin(); it != nums.rend(); ++it) {
		std::cout << *it << " ";
	}
	std::cout << std::endl;
	return 0;
}

Const Iterators

Const iterators provide read-only access to a container's elements, letting you traverse and inspect data while the compiler guarantees you can't accidentally modify any of the underlying values through that iterator.

Example: Const Iterators

cpp
#include <iostream>
#include <vector>

int main() {
	std::vector<int> nums = {1, 2, 3};
	for (auto it = nums.cbegin(); it != nums.cend(); ++it) {
		std::cout << *it << " ";
		// *it = 5; would fail to compile: read-only
	}
	std::cout << std::endl;
	return 0;
}

Iterator Arithmetic and Operations

Random-access containers like vector support arithmetic directly on their iterators — you can compute the distance between two iterators or advance one by an arbitrary number of steps in constant time, unlike simpler forward-only iterators.

Example: Iterator Arithmetic and Operations

cpp
#include <iostream>
#include <vector>

int main() {
	std::vector<int> nums = {10, 20, 30, 40};
	auto it = nums.begin();
	it += 2;
	std::cout << *it << std::endl;
	return 0;
}

Inserter Iterators

Inserter iterators, such as those produced by std::back_inserter, insert new elements into a container rather than overwriting existing ones at that position, which is what lets algorithms like std::copy safely grow a destination container as they run.

Example: Inserter Iterators

cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
	std::vector<int> source = {1, 2, 3};
	std::vector<int> destination;
	std::copy(source.begin(), source.end(), std::back_inserter(destination));
	for (int n : destination) 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.