C++ Iterators
In this page:
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 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: