How do I iterate safely and efficiently with std::vector?

Iterating safely and efficiently over a std::vector in C++ can be achieved through various methods, each with its own advantages. This guide provides an example of how to do this using range-based for loops, iterators, and traditional for loops. We'll also touch on the topics of performance and safety in these different approaches.

Keywords: C++, std::vector, safe iteration, efficient iteration, range-based for loop, iterators, performance.
Description: This article discusses how to iterate safely and efficiently with std::vector in C++. Learn about different methods including range-based for loops, iterators, and traditional for loops to ensure safety and performance in your C++ programs.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    
    // Safe iteration using range-based for loop
    for (const auto &value : vec) {
        std::cout << value << " ";
    }

    std::cout << std::endl;

    // Iterator-based iteration
    for (auto it = vec.begin(); it != vec.end(); ++it) {
        std::cout << *it << " ";
    }

    std::cout << std::endl;

    // Traditional for loop
    for (size_t i = 0; i < vec.size(); ++i) {
        std::cout << vec[i] << " ";
    }

    return 0;
}
    

Keywords: C++ std::vector safe iteration efficient iteration range-based for loop iterators performance.