简体   繁体   English

关于数组的困惑

[英]confusion about arrays

I have an array like that: 我有一个像这样的数组:

int sizes[5] = {1,2,3,4,5};

I want to have 5 different arrays by using the array above. 我想通过使用上面的数组有5个不同的数组。 Because I want each of my arrays to have the size of sizes[i] (0 <= i < 5) . 因为我希望我的每个数组都具有size sizes[i] (0 <= i <5)的大小 How can I do that? 我怎样才能做到这一点? The more I ponder upon this, the more I get confused. 我越想这件事,就会越困惑。 Do I have to use multidimensional arrays or just a simpler solution? 我必须使用多维数组还是仅使用更简单的解决方案? Thanks in advance. 提前致谢。

I demand STL in the thread! 我在线程中需要STL!

std::vector<int> arrays[5];
for (i = 0; i < 5; ++i)
    arrays[i].resize(sizes[i]);

As I understood you question, you need array of arrays which length can be in range [0, 5] (with variable length). 据我了解,您需要一个数组,数组的长度可以在[0,5]范围内(可变长度)。

So there are a lot of choices, I shall offer you 2 of them: 因此,有很多选择,我将为您提供2种选择:

  1. As you marked your question with C++ tag I offer you to refer to STL , which offer a lot of convenient containers and one of them is std::vector which is dynamic array (size of it can vary). 当您用C ++标记标记问题时,我向您提供STL ,它提供了许多方便的容器,其中之一是std::vector ,它是动态数组 (其大小可以变化)。

  2. If you fill convenient with C , then you can use an array of pointers , each of them will be pointer on array. 如果方便地使用C填充,则可以使用一个指针数组 ,每个指针都是数组上的指针

Simple, you just need dynamic memory allocation: 简单,您只需要动态内存分配:

int sizes = {1, 2, 3, 4, 5};
int **arrays;
int i;

arrays = new int*[5];
for(i = 0; i < 5; i++)
    arrays[i] = new int[sizes[i]]

This is a simple thing to start with, but in real life the STL libraries are much more useful. 开始时这很简单,但是在现实生活中,STL库更加有用。 In this code the memory is dynamically allocated, but not released. 在此代码中,内存是动态分配的,但不会释放。 This can result into a memory leak. 这可能导致内存泄漏。 Using std::vector from STL library will save you from the hassle, and provide a easier way. 使用STL库中的std::vector将使您免于麻烦,并提供了更简单的方法。

@Mikhail has shown a good demonstration of using vector s below. @Mikhail在下面显示了使用vector的很好的演示。

to answer the question, yes you do need a multidimensional array in the most efficient case. 要回答这个问题,是的,在最有效的情况下,您确实需要一个多维数组。 An array of arrays, while the elements are dynamically allocated(considering the number of arrays you specified is constant). 数组数组,同时元素是动态分配的(考虑到您指定的数组数是恒定的)。

int *Array[5];
for(int i = 0; i < sizes; i++)
{
    Array[i] = new int[sizes[i]];
}

you now have 5 dynamically allocated arrays ranging from size 0 to size 5. 您现在拥有5个动态分配的数组,范围从大小0到大小5。

You have to use a dynamic allocation, something like this: 您必须使用动态分配,如下所示:

int *arrays[5];
int i = 0;
int sizes[] = {1,2,3,4,5};
for(i = 0; i < 5; i++)
{
    arrays[i] = (int *)malloc(sizes[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM