有没有办法用非常量变量初始化数组?(C++)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/972705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to initialize an array with non-constant variables? (C++)
提问by Aaron
I am trying to create a class as such:
我正在尝试创建一个类:
class CLASS
{
public:
//stuff
private:
int x, y;
char array[x][y];
};
Of course, it doesn't work until I change int x, y;
to
当然,在我更改int x, y;
为之前它不起作用
const static int x = 10, y = 10;
Which is impractical, because I am trying to read the values of x and y from a file. So is there any way to initialize an array with non-contant values, or declare an array and declare its size on different statements? And I know this would probably require the creation of an array class, but I'm not sure where to start on this, and I don't want to create a 2D dynamic list when the array itself is not dynamic, just the size is not known at compile-time.
这是不切实际的,因为我试图从文件中读取 x 和 y 的值。那么有没有办法用非常量值初始化数组,或者声明一个数组并在不同的语句上声明它的大小?而且我知道这可能需要创建一个数组类,但我不确定从哪里开始,并且当数组本身不是动态的时,我不想创建一个 2D 动态列表,只是大小是在编译时未知。
采纳答案by Steve Gury
The compiler need to have the exact size of the class when compiling, you will have to use the new operator to dynamically allocate memory.
编译器在编译时需要具有类的确切大小,您将不得不使用 new 运算符来动态分配内存。
Switch char array[x][y]; to char** array; and initialize your array in the constructor, and don't forget to delete your array in the destructor.
切换字符数组[x][y]; 到字符**数组;并在构造函数中初始化数组,不要忘记在析构函数中删除数组。
class MyClass
{
public:
MyClass() {
x = 10; //read from file
y = 10; //read from file
allocate(x, y);
}
MyClass( const MyClass& otherClass ) {
x = otherClass.x;
y = otherClass.y;
allocate(x, y);
// This can be replace by a memcopy
for( int i=0 ; i<x ; ++i )
for( int j=0 ; j<x ; ++j )
array[i][j] = otherClass.array[i][j];
}
~MyClass(){
deleteMe();
}
void allocate( int x, int y){
array = new char*[x];
for( int i = 0; i < y; i++ )
array[i] = new char[y];
}
void deleteMe(){
for (int i = 0; i < y; i++)
delete[] array[i];
delete[] array;
}
MyClass& operator= (const MyClass& otherClass)
{
if( this != &otherClass )
{
deleteMe();
x = otherClass.x;
y = otherClass.y;
allocate(x, y);
for( int i=0 ; i<x ; ++i )
for( int j=0 ; j<y ; ++j )
array[i][j] = otherClass.array[i][j];
}
return *this;
}
private:
int x, y;
char** array;
};
*EDIT: I've had the copy constructor and the assignment operator
*编辑:我有复制构造函数和赋值运算符
回答by Aaron
use vector.
使用向量。
#include <vector>
class YourClass
{
public:
YourClass()
: x(read_x_from_file()), y(read_y_from_file())
{
my_array.resize(x);
for(int ix = 0; ix < x; ++ix)
my_array[ix].resize(y);
}
//stuff
private:
int x, y;
std::vector<std::vector<char> > my_array;
};
回答by Todd Gardner
Not in that manner, as in c++, c-style array sizes have to be known at compile time, with some vendor specific extensions allowing certain runtime sizes (to enhance compatibility with C99), but not in the situation you are describing (if you are interested, here's a description). The easiest thing to do would be:
不是那种方式,就像在 c++ 中一样,必须在编译时知道 c 样式数组的大小,某些供应商特定的扩展允许某些运行时大小(以增强与 C99 的兼容性),但不是在您所描述的情况下(如果您有兴趣,这里有说明)。最简单的做法是:
std::vector< std::vector<char> > array;
And apply the size in the constructor:
并在构造函数中应用大小:
array.resize(x);
for(std::vector< std::vector<char> >::iterator curr(array.begin()),end(array.end());curr!=end;++curr){
curr->resize(y);
}
There are many advantages of vector over c style arrays, see here
与 c 样式数组相比,vector 有许多优点,请参见此处
回答by Martin York
Put all the memory into one block.
Because it is private you can then get your access methods to retrieve the correct value.
将所有内存放在一个块中。
因为它是私有的,所以您可以使用访问方法来检索正确的值。
Quick example:
快速示例:
#include <vector>
#include <iostream>
class Matrix
{
public:
class Row
{
public:
Row(Matrix& p,unsigned int x)
:parent(p)
,xAxis(x)
{}
char& operator[](int yAxis)
{
return parent.data(xAxis,yAxis);
}
private:
Matrix& parent;
unsigned int xAxis;
};
Matrix(unsigned int x,unsigned int y)
:xSize(x)
,ySize(y)
,dataArray(x*y)
{}
Matrix::Row operator[](unsigned int xAxis)
{
return Row(*this,xAxis);
}
char& data(unsigned int xAxis,unsigned int yAxis)
{
return dataArray[yAxis*xSize + xAxis];
}
private:
unsigned int xSize;
unsigned int ySize;
std::vector<char> dataArray;
};
int main()
{
Matrix two(2,2);
two[0][0] = '1';
two[0][1] = '2';
two[1][0] = '3';
two[1][1] = '4';
std::cout << two[1][0] << "\n";
std::cout << two.data(1,0) << "\n";
}
回答by Steve Jessop
Take a look at boost::multi_array.
回答by Steve Jessop
You can allocate memory to your 2-dimensional array in the constructor and free it in the destructor. The simplest way:
您可以在构造函数中为二维数组分配内存并在析构函数中释放它。最简单的方法:
array = (char **)malloc(sizeof(char *) * x);
if (array) {
for (i = 0; i < x; i++) {
array[i] = (char *)malloc(sizeof(char) * y);
assert(array[i]);
}
}
回答by Mehrdad Afshari
You can't allocate or initialize a global or static array declaratively using non-constant values (compile-time). It's possible for local arrays though (C99 variable sized arrays, as their initializer essentially runs at runtime every time the function is executed).
您不能使用非常量值(编译时)以声明方式分配或初始化全局或静态数组。但是对于本地数组是可能的(C99 可变大小的数组,因为它们的初始值设定项基本上在每次执行函数时在运行时运行)。
For your situation, I suggest using a pointer instead of an array and create the actual array dynamically at runtime (using new
):
对于您的情况,我建议使用指针而不是数组并在运行时动态创建实际数组(使用new
):
class CLASS
{
public:
CLASS(int _x, int _y) : x(_x), y(_y) {
array = new char*[x];
for(int i = 0; i < x; ++i)
array[i] = new char[y];
}
~CLASS() {
for (int i = 0; i < x; ++i)
delete[] array[i];
delete[] array;
}
//stuff
private:
int x, y;
char **array;
};
回答by CookieOfFortune
If the size is not known at compile time, the array is dynamic. What you could do to keep it static is to make them larger than your largest expected size.
如果在编译时大小未知,则数组是动态的。您可以做的保持静态是使它们大于您的最大预期尺寸。
回答by Not Sure
If you want a dynamically sized array as a class member, you need to array new
it and assign that value to a pointer. The char array[size]
syntax is onlyfor statically-sized arrays.
如果您想要一个动态大小的数组作为类成员,您需要对其进行排列new
并将该值分配给一个指针。该char array[size]
语法仅适用于静态大小的数组。
Better yet, you really should use an std::vector< std::vector<char> >
, there are very few good reasons to manually work with dynamically sized arrays these days.
更好的是,你真的应该使用std::vector< std::vector<char> >
,现在很少有充分的理由手动处理动态大小的数组。