现在我们有了 std::array C 风格的数组还有什么用途?
std::array
远远优于 C 数组.即使我想与遗留代码互操作,我也可以使用 std::array::data()
.我有什么理由想要一个老式的数组吗?
std::array
is vastly superior to the C arrays. And even if I want to interoperate with legacy code, I can just use std::array::data()
. Is there any reason I would ever want an old-school array?
推荐答案
除非我遗漏了什么(我没有紧跟标准的最新变化),C 样式数组的大部分用途仍然存在.std::array
确实允许静态初始化,但它仍然不会为您计算初??始化程序.由于在 std::array
之前唯一真正使用 C 样式数组的是静态初始化表大致如下:
Unless I've missed something (I've not followed the most recent changes in the standard too closely), most of the uses of C style arrays still remain. std::array
does allow static initialization, but it still won't count the initializers for you. And since the only real use of C style arrays before std::array
was for statically initialized tables
along the lines of:
MyStruct const table[] =
{
{ something1, otherthing1 },
// ...
};
使用通常的 begin
和 end
模板函数(在C++11) 来迭代它们.没有提到大小,编译器根据初始化器的数量来确定.
using the usual begin
and end
template functions (adopted in
C++11) to iterate over them. Without ever mentionning the size, which the compiler determines from the number of initializers.
我忘记的另一件事:字符串文字仍然是 C 风格的数组;即类型 char[]
.我认为没有人会因为我们有 std::array
就排除使用字符串文字.
Another thing I forgot: string literals are still C style arrays; i.e. with type char[]
. I don't think that anyone would exclude using string literals just because we have std::array
.
相关文章