C++11之range-based for loop

C++11之range-based for loop

96 Hard模式 关注

2018.06.16 22:15 字数 163 阅读 19评论 0喜欢 1

此前,为了遍历数组/列表等结构,我们不得不写出如下的代码结构。

int array[5] = {1,2,3,4,5};
for( int i=0;i<array.size();i++)
{
  // do sth.
}

在C++11中,我们可以像Java中的foreach一样,写出更简洁的循环代码。

int array[5] = {1,2,3,4,5};
for( auto& i : array )
{
  // do sth.
}

对于更复杂的数据结构,新的for循环能更好地提升coding效率

map<string, int> m{ {"a", 1}, {"b", 2}, {"c", 3} };
for( auto it : m )
{
    std::cout << it.first << " : " << it.second << std::endl;
}

对比一下C++11之前的写法:

map<string, int> m{ {"a", 1}, {"b", 2}, {"c", 3} };
for( std::map<string, int>::iterator it = m.begin(); it != m.end(); it++)
{
    std::cout << it->first << ":" << it->second << std::endl;
}

通过共同使用auto以及新的for循环,可以使我们减少对于类型的关注,进而将更多的注意力放在函数功能的实现上。

关于auto的内容可以参考这篇文章 C++11之auto

猜你喜欢

转载自blog.csdn.net/jfkidear/article/details/89196847