可能重复:
Advantages of std::for_each over for loop为什么在for循环中使用std :: for_each?
所以我用一些C++ 11个功能玩弄,我很好奇,为什么的std :: for_each的是有益的。难道它不会更容易,看起来更干净吗?还是因为我习惯这样做?
#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;
}
的foreach的要点循环是看更整洁和更容易为人类比其解释为(;;)同行。虽然 – Akron
正在研究C++ 11功能,但我个人偏向于定期循环。我将在循环中使用auto关键字,并开始(数字)/结束(数字)。使其更加兼容不同类型的数据类型。 – inf