最近我发现了很多例子,其中大部分都是关于 C++ 98 的,反正我已经创建了我的简单数组和一个循环( codepad ):
#include <iostream>
using namespace std;
int main ()
{
string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
return 0;
}
输出:
value of a: Apple
value of a: Banana
value of a: Orange
Segmentation fault
它工作正常,除了最后的分段错误。
我的问题是,这个数组/循环是否做得很好?我正在使用 C++ 11,所以想确保它符合标准并且不能做得更好?
Nope. Totally a wrong way of iterating through an array.
sizeof(texts)
is not equal to the number of elements in the array!The modern, C++11 ways would be to:
std::array
if you want an array whose size is known at compile-time; orstd::vector
if its size depends on runtimeThen use range-for when iterating.
Live example
You may ask, how is
std::array
better than the ol' C array? The answer is that it has the additional safety and features of other standard library containers, mostly closely resemblingstd::vector
. Further, The answer is that it doesn't have the quirks of decaying to pointers and thus losing type information, which, once you lose the original array type, you can't use range-for orstd::begin/end
on it.