我是C++新手。我试图创建一个多维数组。这段代码有什么问题?C++ - 你如何创建多维数组?
int sorted_array[] = {{2, 3}, 5, 7};
它给了我这个错误。
error: braces around scalar initializer for type 'int'
谢谢。
我是C++新手。我试图创建一个多维数组。这段代码有什么问题?C++ - 你如何创建多维数组?
int sorted_array[] = {{2, 3}, 5, 7};
它给了我这个错误。
error: braces around scalar initializer for type 'int'
谢谢。
声明多维数组时,必须指定除第一个之外的所有维。
例如
int sorted_array[][2] = {{2, 3}, {5}, {7}};
这相当于:
int sorted_array[3][2] = {{2, 3}, {5}, {7}};
不能使用:
int sorted_array[][] = {{2, 3}, {5}, {7}};
和期望编译器推断2
第二维度。
很好的解释,谢谢。 –
有创建多维数组的许多方式:
int sorted_array[2][2] = {{2,3},{5,7}};
这产生一个阵列,其存储2名整型阵列存储2个整数
,但我会建议的载体
#include <vector>
std::vector<std::vector<int> > sorted_array = {{2,3},{5,7}};
这是同样的事情,但矢量有更多的功能
你可以访问它们都以同样的方式:
sorted_array[0][1] = 3;
值得一提的是,当编译时已知固定尺寸时,应使用'std :: array'。 –
其他的答案是正确的,当然,但它是值得一提的是,创建一个二维数组的便捷方式是包装扁平行主要std::vector
一类如下:
template<typename _Ty>
class matrix {
// used to enabled [][] overload on matrix objects
class proxy_row_vector {
public:
proxy_row_vector(std::vector<_Ty>& _vec, std::size_t _cols, std::size_t _row_index)
: vec(_vec), cols(_cols), row_index(_row_index) {}
const _Ty& operator[](std::size_t col_index) const {
return vec[row_index*cols + col_index];
}
_Ty& operator[](std::size_t col_index) {
return vec[row_index*cols + col_index];
}
private:
std::vector<_Ty>& vec;
std::size_t cols;
std::size_t row_index;
};
public:
matrix(std::size_t _rows, std::size_t _cols)
: mtx(_rows*_cols), rows(_rows), cols(_cols) {}
proxy_row_vector operator[](std::size_t row_index) const {
return proxy_row_vector(mtx, cols, row_index);
}
proxy_row_vector operator[](std::size_t row_index) {
return proxy_row_vector(mtx, cols, row_index);
}
std::vector<_Ty>::const_iterator cbegin() const {
return mtx.cbegin();
}
std::vector<_Ty>::const_iterator cend() const {
return mtx.cend();
}
// ... other iterator access methods ...
private:
std::vector<_Ty> mtx;
std::size_t rows;
std::size_t cols;
};
然后就可以简单地如下创建一个二维数组和操作使用索引或迭代元素:
matrix<int> m(3,3); // default initialises 3x3 matrix of ints
m[0][0] = 1; // set first row, first column element to 1
for (auto& el : m)
el = 4; // fill m with value 4
这样做的优点方法是简单的迭代器支持,允许您使用任何标准算法来操纵矩阵元素,并为任何二维元素阵列提供方便的管理界面。
注:以上级matrix
是很小的,你会明显地要提供进一步的方法和构造函数(如at
方法边界检查,以及一个rows()
方法和发现的行数columns()
方法,矩阵的列)。
在C++中,你通常不使用原始数组。 C++中的多维数组应该是'std :: array,DIM2> sorted_array;'。 –