How to Use Iterators in C++

How do I use iterators with different containers in C++?

To use iterators with different containers in C++, follow these steps:

  1. Include the headers for the containers you plan to use.
  2. Use the begin() and end() methods to get iterators to the start and end of the container.
  3. Use a loop to traverse the container using the iterators.

Here's an example with std::vector and std::forward_list:

#include <vector>
#include <forward_list>
#include <iostream>
void Log(auto Iterator, auto End) {
  while (Iterator != End) {
    std::cout << *(Iterator++) << ", ";
  }
}

int main() {
  std::forward_list<int> List{1, 2, 3};
  std::cout << "std::forward_list<int>:\n";
  Log(List.begin(), List.end());

  std::vector<int> Vector{1, 2, 3};
  std::cout << "\n\nstd::vector<int>:\n";
  Log(Vector.begin(), Vector.end());
}
std::forward_list<int>:
1, 2, 3,

std::vector<int>:
1, 2, 3,

Iterators and Ranges

This lesson offers an in-depth look at iterators and ranges, emphasizing their roles in container traversal

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

What is a Range in C++?
What is a range in C++ and how is it different from an iterator?
Using Range-Based For Loops in C++
How do I use range-based for loops in C++?
Passing by Reference in Range-Based For Loops
Why should I pass by reference in range-based for loops in C++?
Understanding Range Categories in C++
What are the different categories of ranges in C++?
Using Concepts in C++
How do I use concepts in C++ to check if a type is a range?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant