【在 O*******d 的大作中提到】 : 容器不能放reference,因为reference需要在产生时就initialize。例如, : vectora(5) 无法生成。 同样的道理还有 new int &[5];
d*p
27 楼
You cannot use std::vector. But you can use std::vectorreference_wrapper >. So int i = 9; int& j = i; std::vector > myvec; myvec.push_back(boost::reference_wrapper(i); myvec.push_back(boost::reference_wrapper(j); ++i; // now both elements in vector become 10. Basically it is a wrapper of a pointer which always points to an initialized variable (not out of scope).
I think it is Ok, although not as handy as BOOST_FOREACH, which really achieves the level of expressiveness as Python and Perl. The only inconvenience for using std::for_each is you have to explicitly define your functor - for really simple tasks it looks an overkill compared with a hand written loop. I however really hate for-iterator stuff - in a team environment other people may get lazy and modify the loop in a way that readability will be harmed. So, using high level construct like for_each