在 C++ 处使用 for 循环初始化一系列数组

发布于 2024-11-03 07:00:58 字数 297 浏览 0 评论 0原文

我尝试使用 for 循环创建一系列多维数组。用户应输入要初始化的数组的数量。我想要这样的东西:

int i;
printf("Enter the number of arrays you want: ");
scanf("%d",i)
for(int j=0;j<i;j++){
     long double x(j)[size][size];
}

如果我输入 5,我想要 x0、x1、x2、x3 和 x4。

有可能吗?

感谢您的帮助。

此致, 埃姆雷.

I try to create series of multidimensional arrays with for loops. User should input the number of arrays to be initialized. I want something like this:

int i;
printf("Enter the number of arrays you want: ");
scanf("%d",i)
for(int j=0;j<i;j++){
     long double x(j)[size][size];
}

if I input 5, I want to have x0, x1, x2, x3 and x4.

Is it possible at all??

Thank you for any help.

Best Regards,
Emre.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小矜持 2024-11-10 07:00:58

编辑:刚刚注意到您正在使用 C++。在这种情况下,std::vector绝对是最方便的解决方案。如果您对如何使用 C 风格的普通数组执行此操作感到好奇,请继续阅读...


您不能这样做。你需要做的是创建一个 3 维数组(或一个 2 维数组的数组,这取决于你的观点......)

与 C 的情况一样,内存分配是一个痛苦......你可以静态地allocate:

long double x[N][size][size];

(N 在编译时确定。确保它足够大。
另外,如果 N 确实很大,请以静态方式声明数组(作为全局变量或使用 static 关键字)。如果你不这样做,你可能会得到堆栈溢出。)

或者你可以使用动态内存分配:

long double (*x)[size][size]; // x is a pointer to size by size arrays
x = malloc(n * sizeof(*x));
//You can now use x[j][a][b]...

也许使用 typedef 看起来会更好(即使我不能 100% 确定我在上一个例子中得到了正确的数组声明...... ):

typedef long double typename_here[size][size];
typename_here *x;
x = malloc(n * sizeof(typename_here);

顺便说一句,您当前的代码不起作用的原因是

  1. x(j) 语法是虚构的:)
  2. 在循环内声明的变量是该块的内部变量。这意味着您无法在循环体之后访问它们。

Edit: Just noticed you are using C++. In this case, std::vector is definitely the most convenient solution. If you are curious about how to do this with plain arrays, C style, then read on...


You can't do it like this. What you need to do is create a 3 dimensional array (or an array of 2-dimensional arrays, depending on your point of view...)

As is always the case with C, memory allocation is a pain... You can statically allocate:

long double x[N][size][size];

(N is determined at compile time. Make sure you have it large enough.
Also if N is really big, declare the array stactically (either as a global variable or with the static keyword). If you don't you can get a stack-overflow.)

Or you can use dynamic memory allocation:

long double (*x)[size][size]; // x is a pointer to size by size arrays
x = malloc(n * sizeof(*x));
//You can now use x[j][a][b]...

Maybe things look better with a typedef (even I am not 100% sure I got that array ceclaration right in the last example...):

typedef long double typename_here[size][size];
typename_here *x;
x = malloc(n * sizeof(typename_here);

BTW, the reason your current code doesn't work is

  1. The x(j) syntax is ficticious :)
  2. Variables declared inside a loop are internal to that block. This means you can't access them after the loop body.
许久 2024-11-10 07:00:58

如果您使用 C++,您最好使用 std::vector 作为:

//single dimensional array of double of size 20
std::vector<double>  v1double (20);      
//use like v[i] where  0 <= i < 20

//two dimensional array of double of size  (10 * 20)
std::vector<std::vector<double> >  v2double(10, v1double ); 
//use like v[i][j] where  0 <= i < 10 and 0 <= j < 20

//three dimensional array of double of size (5 * 10 * 20)
std::vector<std::vector<std::vector<double> >  v3double (5, v2double); 
//use like v[i][j][k] where  0 <= i < 5 and 0 <= j < 10 and 0 <= k < 20

If you're working in C++, you better should be using std::vector as:

//single dimensional array of double of size 20
std::vector<double>  v1double (20);      
//use like v[i] where  0 <= i < 20

//two dimensional array of double of size  (10 * 20)
std::vector<std::vector<double> >  v2double(10, v1double ); 
//use like v[i][j] where  0 <= i < 10 and 0 <= j < 20

//three dimensional array of double of size (5 * 10 * 20)
std::vector<std::vector<std::vector<double> >  v3double (5, v2double); 
//use like v[i][j][k] where  0 <= i < 5 and 0 <= j < 10 and 0 <= k < 20
烧了回忆取暖 2024-11-10 07:00:58

一组多维数组与多一个维度的多维数组是一样的。

另外,关于内置数组的一些事情:

  • 在 C++ 中,内置数组维度必须基于编译时常量。您无法计算大小、从文件中读取它、从用户输入中获取它等。
  • 要创建具有可变大小的内置数组,您必须分配内存,并像指针一样使用它
  • 要为内置数组分配内存-in 数组要在 C 和 C++ 之间移植,您必须使用 malloc,并确保稍后对从 malloc 获得的所有内容调用 free (有时很难做到正确)

如果您使用的是 C++,并且不需要使用 C 编译器编译代码,我建议使用 vector 而不是内置数组。向量不必具有恒定的大小,并且可以在您想要调整大小时调整大小,通常无需在代码中调用 mallocnew

一种方法这看起来像:

#include<iostream>
#include<vector>

int main(int argc, char* argv[])
{
    std::cout << "Enter the number of arrays you want:" << std::endl;

    const int size = 4;
    const int initial_value = 0;
    int i;
    std::cin >> i;

    std::vector<int> sub_sub_array(size, initial_value);
    std::vector<std::vector<int> > sub_array(size, sub_sub_array);
    std::vector<std::vector<std::vector<int> > > array(i, sub_array);

    array[0][1][2] = 5;

    // Print out the full array contents
    for(size_t i = 0; i < array.size(); ++i)
    {
        for(size_t j = 0; j < size; ++j)
        {
            for(size_t k = 0; k < size; ++k)
            {
                std::cout << "(" << j << ", " << k << ") - " << array[i][j][k] << ", ";
            }
            std::cout << "\n";
        }
        std::cout << "\n";
    }
}

输入您想要的阵列数量:
2

(0, 0) - 0, (0, 1) - 0, (0, 2) - 0, (0, 3) - 0,
(1, 0) - 0, (1, 1) - 0, (1, 2) - 5, (1, 3) - 0,
(2, 0) - 0, (2, 1) - 0, (2, 2) - 0, (2, 3) - 0,
(3, 0) - 0, (3, 1) - 0, (3, 2) - 0, (3, 3) - 0,

(0, 0) - 0, (0, 1) - 0, (0, 2) - 0, (0, 3) - 0,
(1, 0) - 0, (1, 1) - 0, (1, 2) - 0, (1, 3) - 0,
(2, 0) - 0, (2, 1) - 0, (2, 2) - 0, (2, 3) - 0,
(3, 0) - 0, (3, 1) - 0, (3, 2) - 0, (3, 3) - 0,

编辑:

上述解决方案的唯一问题是您可能能够也可能无法在需要内置数组的代码中使用它。从你的评论来看,你需要它。

如果您现有的代码可以一次接受一行,那么上述解决方案将起作用。如果它只能接受二维数组,则必须使用不同的向量结构。请参阅此问题了解原因:

传递嵌套 C++ 向量作为内置样式多维数组

如果您需要一组连续的二维数组,这里有一些选项:

std::vector<int*> array_instances(i);
for(size_t j = 0; j < array_instances.size(): ++j)
    array_instances[j] = new int[size * size];

for(size_t j = 0; j < array_instances.size(); ++j)
    existing_code(array_instances[j]);

// When done with the arrays
for(size_t j = 0; j < array_instances.size(): ++j)
    delete[] array_instances[j]; // Make sure to include the brackets after "delete"

或者:

std::vector<int> template_array(size * size, 0);
std::vector<std::vector<int> > array_instances(i, template_array);

for(size_t j = 0; j < array_instances.size(); ++j)
    existing_code(&array_instances[j][0]);

A set of multi-dimensional arrays is the same thing as a multi-dimensional array with one more dimension.

Also, a couple of things about built-in arrays:

  • In C++, the built-in array dimensions must be based off a compile time constant. You can't calculate the size, read it from a file, get it from user input, etc
  • To create a built-in array with variable size, you must allocate memory, and use it like a pointer
  • To have an allocation for a built-in array be portable between C and C++, you must use malloc, and ensure that later you call free on everything you got from malloc (which can sometimes be very hard to get right)

If you are using C++, and don't need to compile your code with a C compiler, I recommend using a vector instead of a built-in array. Vectors don't have to have a constant size, and can be resized whenever you feel like resizing them, often without calling malloc or new in your code

One way to go about this would look like:

#include<iostream>
#include<vector>

int main(int argc, char* argv[])
{
    std::cout << "Enter the number of arrays you want:" << std::endl;

    const int size = 4;
    const int initial_value = 0;
    int i;
    std::cin >> i;

    std::vector<int> sub_sub_array(size, initial_value);
    std::vector<std::vector<int> > sub_array(size, sub_sub_array);
    std::vector<std::vector<std::vector<int> > > array(i, sub_array);

    array[0][1][2] = 5;

    // Print out the full array contents
    for(size_t i = 0; i < array.size(); ++i)
    {
        for(size_t j = 0; j < size; ++j)
        {
            for(size_t k = 0; k < size; ++k)
            {
                std::cout << "(" << j << ", " << k << ") - " << array[i][j][k] << ", ";
            }
            std::cout << "\n";
        }
        std::cout << "\n";
    }
}

Enter the number of arrays you want:
2

(0, 0) - 0, (0, 1) - 0, (0, 2) - 0, (0, 3) - 0,
(1, 0) - 0, (1, 1) - 0, (1, 2) - 5, (1, 3) - 0,
(2, 0) - 0, (2, 1) - 0, (2, 2) - 0, (2, 3) - 0,
(3, 0) - 0, (3, 1) - 0, (3, 2) - 0, (3, 3) - 0,

(0, 0) - 0, (0, 1) - 0, (0, 2) - 0, (0, 3) - 0,
(1, 0) - 0, (1, 1) - 0, (1, 2) - 0, (1, 3) - 0,
(2, 0) - 0, (2, 1) - 0, (2, 2) - 0, (2, 3) - 0,
(3, 0) - 0, (3, 1) - 0, (3, 2) - 0, (3, 3) - 0,

Edit:

The only problem with the solution above is that you may or may not be able to use it in code that expects a built-in array. Judging from your comments, you need it to.

If your existing code can accept one row at a time, then the above solution will work. If it can only accept a 2d array, you'll have to use a different vector structure. See this question for why:

Pass nested C++ vector as built-in style multi-dimensional array

If you need a set of contiguous 2d arrays, here are some options:

std::vector<int*> array_instances(i);
for(size_t j = 0; j < array_instances.size(): ++j)
    array_instances[j] = new int[size * size];

for(size_t j = 0; j < array_instances.size(); ++j)
    existing_code(array_instances[j]);

// When done with the arrays
for(size_t j = 0; j < array_instances.size(): ++j)
    delete[] array_instances[j]; // Make sure to include the brackets after "delete"

Or:

std::vector<int> template_array(size * size, 0);
std::vector<std::vector<int> > array_instances(i, template_array);

for(size_t j = 0; j < array_instances.size(); ++j)
    existing_code(&array_instances[j][0]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文