C++ traversal of for loop

·

1 min read

Method 1(index-based iteration)

std::vector<int> v = { 1, 2, 3, 4, 5};
for (size_t i = 0; i < v.size(); ++i)
{
    std::cout << v[i];
}

Method 2(range-for loop)

std::vector<int> v = { 1, 2, 3, 4, 5};
for (const int& i : v) // Access by const reference
{
    std::cout << i;
}

for (auto i : v) // Access by value
{
    std::cout << i;
}

Method 3(iterator-based iteration)

std::vector<int> v = { 1, 2, 3, 4, 5};
for (auto it = v.begin(); it != v.end(); ++it)
{
    std::cout << *it;
}

Method 4(STL for_each algorithm + lambda)

std::vector<int> v = { 1, 2, 3, 4, 5};
std::for_each(v.begin(), v.end(), [](const int& i) {
     std::cout << i;
});