C++11之for

C++11中新加了基于范围的for循环,可以对集合/数组/初始化列逐个访问,这种用法在其他高级语言里早有实现,现在C++终于支持了.

for的新特性是的代码更加的简洁:

//原来的方法
for (std::vector<int>::const_iterator itr = myvec.cbegin(); itr != myvec.cend(); ++itr)
//C++11中auto和for新特性结合
for (auto& x : myvec)

简直屌爆了有木有.

对于自定义的集合类型支持foreach,只需实现beginend函数即可,因为内置的STL模板会自动适配:

template <typename Container>
auto begin (Container& cont) -> decltype (cont.begin());

template <typename Container>
auto begin (const Container& cont) -> decltype (cont.begin());

template <typename Container>
auto end (Container& cont) -> decltype (cont.end());

template <typename Container>
auto end (const Container& cont) -> decltype (cont.end());