Iterating over a vector works:
std::vector<int> collection = {2, 3, 4, 5435345, 2};
std::for_each(collection.begin(), collection.end(), [](int& i){cout << i << endl;});
but not over a set (compile error):
std::set<int> collection = {2, 3, 4, 5435345, 2};
std::for_each(collection.begin(), collection.end(), [](int& i){cout << i << endl;});
Why can’t I iterate over a std::set with std::for_each?
Bonus question:
Also, I would like to change the int& in the lambda’s argument to auto&, why can’t this be automatically deduced?
std::set<T>::value_typeisT const, notT; consequently, the argument to your lambda must be a value type (i.e., copy) orint const&(and technically, orint const volatile&), notint&. I.e., this works:Because the standard says it can’t; historically, I believe this was due to overly-complicated interactions between lambdas and concepts (before concepts were removed from the draft).
However, I hear rumors that the first defect reports to the new (C++11) standard will address exactly this, so it’s possible that you’ll see support for this added to your compiler of choice within the next year or two.EDIT: Oh, look, C++14 now has polymorphic lambdas…