Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use std::for_each over a for loop? [duplicate]

Tags:

c++

c++11

Possible Duplicate:
Advantages of std::for_each over for loop

So I was playing around with some C++11 features and I'm curious as to why std::for_each is beneficial. Wouldn't it be easier and look cleaner to do a for loop or is it because I'm so used to doing it this way?

#include <iostream>
#include <tuple>
#include <vector>
#include <algorithm>

typedef std::tuple<int, int> pow_tuple;

pow_tuple pow(int x)
{
    return std::make_tuple(x, x*x);
}

void print_values(pow_tuple values)
{
    std::cout << std::get<0>(values) << "\t" << std::get<1>(values) << std::endl;
}

int main(int argc, char** argv)
{
    std::vector<int> numbers;
    for (int i=1; i < 10; i++)
        numbers.push_back(i);
    std::for_each(numbers.begin(), numbers.end(),
        [](int x) { print_values(pow(x)); }
        );

    std::cout << "Using auto keyword:" << std::endl;
    auto values = pow(20);
    print_values(values);
    return 0;
}
like image 221
David Avatar asked Nov 02 '11 18:11

David


3 Answers

the standard algorithms handle all of the looping issues correctly, reducing the chance of making one-off errors and such, allowing you to focus on the calculation and not the looping.

like image 161
drdwilcox Avatar answered Sep 24 '22 06:09

drdwilcox


It depends somewhat on the local coding conventions, but there are two potential advantages. The first is that it states clearly that the code iterates over all of the elements in the sequence; unless the local coding conventions say otherwise (and they are enforced), you have to consider that some cowboy programmer might have inserted a break. The second is that it names the operation you are performing on each element; this once can easily be handled by calling a function in the loop, and of course, really trivial operations may not need a name.

There's also the advantage, at least if you aren't yet using C++11, that you don't have to spell out the iterator types; the spelled out iterator types create a lot of verbiage, in which the important logic can get lost or overlooked.

like image 35
James Kanze Avatar answered Sep 22 '22 06:09

James Kanze


one could say that this form allows you write this piece of code without the unnecessary index to manipulate and make mistakes with.

It is also an idiom which exists in other languages, and since you are getting anonymous functions, this feature can be a good example of higher level functions (educational purpose?).

I agree that it does not feel like c++ ...

like image 41
Simon Bergot Avatar answered Sep 23 '22 06:09

Simon Bergot