阵列的C ++矢量 [英] C++ vector of arrays

查看:209
本文介绍了阵列的C ++矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这项工作:

std::pair<int, int> p = {1,2};
std::vector<std::pair<int, int>> vp = { {1,2}, {3,4} };

但是,这不?

std::array<int, 2> a = {1,2}; // still ok
std::vector<std::array<int, 2>> va = { {1,2}, {3,4} };

使用G ++ 4.5.1与 -std =的C ++ 0x ,第二行失败:

错误:无法转换'{{1,2},{3,4}} '的std ::矢量&lt; STD ::阵列&LT; INT,2U&GT; &GT;

感谢

推荐答案

不幸的是,的std ::阵列没有一个初始化列表构造。事实上,它拥有的没有的任何用户定义的构造函数 - 这个功能是由C ++ 03的后遗症,其中省略所有用户定义的构造是为了使C-风格的大括号初始化的唯一途径。它是IMHO在当前的标准中的缺陷。

Unfortunately, std::array does not have an initializer list constructor. Indeed, it has no user-defined constructor whatsoever -- this "feature" is a leftover from C++03 where omitting all user-defined constructors was the only way to enable the C-style brace initialization. It is IMHO a defect in the current standard.

那么,为什么不内置括号的初始化工作在这种情况下?让我们来看看的std ::阵列看起来引擎盖下:

So why doesn't built-in brace initialization work in this case? Let's see what std::array looks like under the hood:

template <typename T, int i> struct array {
    T data[i];
    // ...
}

好了,并不意味着我们不得不使用的的括号中的初始化(一对用于阵列,另一对为数据成员?

Ok, so doesn't that mean we'd have to use double braces in the initializer (one pair for array, another pair for the data member?

std::array<int, 2> a = { {1, 2} };

C(因此C ++)拥有约的梅开二度省音的,允许内括号遗漏,除非出现混淆一个特殊的规则。 阵列利用此功能,让我们写

C (and consequently C++) has a special rule about brace elision, permitting the omission of the inner braces unless there is an ambiguity. array exploits this feature, allowing us to write

std::array<int, 2> a = { 1, 2 };

那么,为什么没有在原岗位工作的例子吗?由于梅开二度省音在C风格集合初始化的情况下才允许,而不是是否有什么复杂的更多参与,如用户自定义的初始化列表构造。

So why doesn't the example in the original post work? Because brace elision is only permitted in the context of a C-style aggregate initialization, not if there's anything more complicated involved, such as an user-defined initializer list constructor.

下面的的工作,不过,因为丑陋的,因为它是:

The following should work, though, as ugly as it is:

std::vector<std::array<int, 2>> vp = { {{1,2}}, {{3,4}} };

这是不是这样,至少在GCC 4.5和gcc 4.6其实,在我看来,以指示编译器错误。我不能完全肯定,虽然。

The fact that it does not, at least on gcc 4.5 and gcc 4.6, seems to me to indicate a compiler bug. I'm not completely sure about it, though.

这问题有点相关的:<一href=\"http://stackoverflow.com/questions/5549524/how-do-i-initialize-a-member-array-with-an-initializer-list\">How我做初始化与initializer_list成员阵列?

这篇关于阵列的C ++矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆