我有这个代码:
#include <array>
int main(int, char **argv)
{
std::array<int, 3> a = {1,2,3};
}
Run Code Online (Sandbox Code Playgroud)
这编译很好(-std = c ++ 11),但如果你包含-Wall它会发出我不明白的警告:
clang_pp_error.cpp:5:28: warning: suggest braces around initialization of subobject [-Wmissing-braces]
std::array<int, 3> a = {1,2,3};
^~~~~
{ }
Run Code Online (Sandbox Code Playgroud) 我在C++中使用ranged有点麻烦.我正在尝试使用它来显示元素和int数组(int []),当我在main函数上执行它时,它完全正常,如:
int main(int argc, char const *argv[]) {
int v[] = {3, 4, 6, 9, 2, 1};
for (auto a : v) {
std::cout << a << " ";
}
std::cout << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到了我想要的和预期的输出,即:
3 4 6 9 2 1
Run Code Online (Sandbox Code Playgroud)
但是当我尝试在函数内部使用ranged时,事情变得有点奇怪,例如我遇到了这段代码的问题:
void printList(int *v);
int main(int argc, char const *argv[]) {
int v[] = {3, 4, 6, 9, 2, 1};
printList(v);
return 0;
}
void printList(int *v) {
for (auto a : v) {
std::cout << …Run Code Online (Sandbox Code Playgroud) 以下是在C++ 11中声明和初始化数组的8种方法g++:
/*0*/ std::array<int, 3> arr0({1, 2, 3});
/*1*/ std::array<int, 3> arr1({{1, 2, 3}});
/*2*/ std::array<int, 3> arr2{1, 2, 3};
/*3*/ std::array<int, 3> arr3{{1, 2, 3}};
/*4*/ std::array<int, 3> arr4 = {1, 2, 3};
/*5*/ std::array<int, 3> arr5 = {{1, 2, 3}};
/*6*/ std::array<int, 3> arr6 = std::array<int, 3>({1, 2, 3});
/*7*/ std::array<int, 3> arr7 = std::array<int, 3>({{1, 2, 3}});
Run Code Online (Sandbox Code Playgroud)
根据严格标准(以及即将推出的C++ 14标准),正确的是什么?什么是最常见的/使用的和那些要避免的(以及为什么)?
我有一个struct包含数组,我想将初始化列表传递给struct的构造函数以转发到数组.为了说明,我试过:
#include <initializer_list>
struct Vector
{
float v[3];
Vector(std::initializer_list<float> values) : v{values} {}
};
int main()
{
Vector v = {1, 2, 3};
}
Run Code Online (Sandbox Code Playgroud)
error: cannot convert ‘std::initializer_list<float>’ to ‘float’ in initialization
我尝试使用括号而不是大括号,v但这给出了错误:
error: incompatible types in assignment of ‘std::initializer_list<float>’ to ‘float [3]’
尝试这样做的主要动机是避免clang生成的以下警告:
template <int N>
struct Vector
{
float v[N];
};
template <>
struct Vector<2>
{
float x, y;
};
int main()
{
Vector<2> v2 = {1.0f, 2.0f}; // Yay, works …Run Code Online (Sandbox Code Playgroud)