【发布时间】:2016-07-13 10:48:12
【问题描述】:
虽然我对 Java 中的 C 和 OOP 非常了解,但我开始深入研究 C++ 及其特殊性。我已经阅读了有关 C++ 的所有基本内容,但我仍然对一些 C++11 特定的东西感到困惑,无论是语法还是性能方面。其中包括容器迭代器,我发现它以多种语法形式实现(例如range-based loops)。
我想知道其中哪一个是完全等效的,为什么要使用其中一个或另一个,以及对性能有什么影响。
a)auto 与显式声明:
是否始终支持auto?除了代码可读性问题,为什么程序员更喜欢显式声明?
list<int>::const_iterator i = myIntList.begin(); /* Option a1 */
auto i = myIntList.begin(); /* Option a2 */
for(auto i : myIntList) { ... } /* Option a3 */
for(int i : myIntList) { ... } /* Option a4 */
b) 紧凑形式与扩展循环形式
list<int> l = {1, 2, 3, ...};
for(auto i : l) { ... } /* Option b1 */
for(auto i = l.begin(); i != l.end(); ++i) { ... } /* Option b2 */
c) 常量、非常量/访问类型
为什么/什么时候希望在循环体中有引用或常量?
/* Constant/non-constant: */
for(list<int>iterator i = l.begin(); ...) { ... } /* Option c1 */
for(list<int>const_iterator i = l.begin(); ...) { } /* Option c2 */
for(const int& i : list) { ... } /* Option c3 */
for(int& i : list) { ... } /* Option c4 */
/* Access by reference/by value: */
for(auto&& i : list) { ... } /* Option c5 */
for(auto i : list) { ... } /* Option c6 */
d) 循环的退出条件:
/* Option d1: end is defined within the start condition or outside the loop. */
for(auto i = l.begin(), end = l.end(); i != end; ++i) { ... }
/* Option d2: end is defined in the continue condition. */
for(auto i = l.begin(); i != l.end(); ++i) { ... }
也许它们中的大多数是相同的,也许选择一个或另一个选项只对给定的循环体有意义,但我想知道允许这么多可能的方式来编程相同行为的目的是什么。
【问题讨论】:
-
您指的是标准容器吗?
-
也迭代元素与迭代器。我想你在这里问的太多了。
-
I wonder what's the purpose of allowing so many possible ways of programming the same behaviour.因为该语言必须保持与旧版本的兼容性,同时添加改进的语法。就这么简单。您问的其他所有问题都已在其他地方讨论到死。标记为过于宽泛。 -
@underscore_d 实际上,大多数“可能的方式”实际上做了不同的事情。
-
@juanchopanza 是的,我的意思是 range-
for通常是可以使用显式基于迭代器的语法指定的各种事物的简写,但可能过于简单化了。我仍然认为这个“问题”实际上是很多问题,所有这些问题都在其他地方得到了充分的回答,无论是在 SO 上还是在一个好的 C++ 参考中。