Iterators and Ranges

How to Use Iterators in C++

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

Abstract art representing computer programming

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,
This Question is from the Lesson:

Iterators and Ranges

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Iterators and Ranges

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved