这样的初始值设定项列表在C++11中合法吗
Is initializer list like this legal in C++11?
我阅读了C++入门第5版,其中介绍了最新的标准支持列表初始值设定项。
我的测试代码是这样的:
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::ispunct;
int main(int argc, char *argv[])
{
vector<int> a1 = {0,1,2};
vector<int> a2{0,1,2}; // should be equal to a1
return 0;
}
然后我使用Clang 4.0:
bash-3.2$ c++ --version
Apple clang version 4.0 (tags/Apple/clang-421.0.60) (based on LLVM 3.1svn)
Target: x86_64-apple-darwin12.2.0
Thread model: posix
并像这样编译:
c++ -std=c++11 -Wall playground.cc -o playground
然而,它的抱怨是这样的:
playground.cc:13:17: error: no matching constructor for initialization of
'vector<int>'
vector<int> a1 = {0,1,2};
^ ~~~~~~~
/usr/include/c++/4.2.1/bits/stl_vector.h:255:9: note: candidate constructor
[with _InputIterator = int] not viable: no known conversion from 'int'
to 'const allocator_type' (aka 'const std::allocator<int>') for 3rd
argument;
vector(_InputIterator __first, _InputIterator __last,
^
/usr/include/c++/4.2.1/bits/stl_vector.h:213:7: note: candidate constructor
not viable: no known conversion from 'int' to 'const allocator_type'
(aka 'const std::allocator<int>') for 3rd argument;
vector(size_type __n, const value_type& __value = value_type(),
我检查了Clang的C++支持状态,看起来它应该已经支持Clang 3.1中的Initializer列表了。但是为什么我的代码不起作用。有人对此有想法吗?
代码是合法的,问题在于编译器+stdlib设置。
苹果的Xcode附带了GNUC++标准库libstdc++的4.2.1版本(请参阅https://stackoverflow.com/a/14150421/981959详细信息),并且该版本比C++11早了很多年,所以它的std::vector
没有初始化器列表构造函数。
要使用C++11功能,您需要安装并使用更新的libstdc++,或者告诉clang使用苹果自己的libc++库,这可以通过-stdlib=libc++
选项来实现。
相关文章:
- 在 C++11 及更高版本中,有没有办法初始化初始值设定项列表中的向量?
- C++11 中的混合列表初始化
- 我将 Makefile 更改为 C++11 版本,但仍然收到列表初始值设定项错误
- 使用 C++11 时列表中出现编译错误
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- C++11 默认类成员初始化与初始值设定项列表同时
- 在编译时使用 gnu++11 过滤值列表,不使用 stdlib(Arduino 环境)
- 将类成员指针传递给 Lambda 捕获列表 c++11
- 为什么 GCC 6.3 在没有显式 C++11 支持的情况下编译此大括号初始化列表代码
- G++ - 警告:扩展初始值设定项列表仅适用于 -std=C++11 或 -std=GNU++11
- 有没有办法在旧版本的 c++ 中实现初始值设定项列表(有点)(在 c++11 之前)
- 扩展初始化器列表仅可用-STD = C 11或-STD = GNU 11中的C
- C++11 在列表到映射(或其他容器)之间移动元素
- 子类对象列表重新解释为基类对象列表?(C++11).
- C 11联合会的空列表初始化 - 是否保证可以初始化工会的全长
- 我写了一个函数来删除循环链接列表中的第 1 个节点,但输出显示无限次"55 44 33 22 11 99",那么我该如何解决呢?
- 分配列表和初始化器列表之间 C++11 缩小的差异
- MSVC 19.11 / Visual C 2017:尺寸1和size_t类型的初始化列表误解
- C 11:列表限制如何在用户定义的对象中分配值
- c++11 列表初始化的不同行为