可能重複:
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