简体   繁体   English

C ++动态分配数组

[英]C++ dynamic allocated array

I'm doing some assignment and got stuck at one point here. 我正在做一些作业,被困在这里。 I am trying to write an list_add() function. 我正在尝试编写一个list_add()函数。 The first functionality of it is to add values to the array. 它的第一个功能是将值添加到数组。 The second functionality for it is to increase the size of the array. 它的第二个功能是增加阵列的大小。 So it works much like a vector. 因此,它的工作原理很像向量。 I dunno if I get it right though. 如果我做对了,我不知道。 What I tried is to create a new dynamic allocated array which is larger than the old one, and then copy over all the values to the new array. 我试图创建一个比旧数组更大的新动态分配数组,然后将所有值复制到新数组中。

Is it the right approach? 这是正确的方法吗?

Here's the main body 这是主体

int main()
{
    const int N = 7;

    //declaring dynamic array allocation
    int* list = new int[N];

    int used = 0, a_val;
    for(int i=0;i<11;i++)
    {
        list_add(list, used, N, i);
    }

    cout << endl << "Storlek: " << N << endl << endl;
    cout << "Printar listan " << endl;
    for(int i=0;i<used;i++)
    {
        cout << list[i] << ". ";
    }

}

Here's the function 这是功能

bool list_add(int *list, int& space_used, int max_size, int value)
{

    if(max_size-space_used > 0)
    {
        *(list+(max_size-space_used-1)) = value;
        space_used++;
        return true;
    }
    else
    {
        cout << "Increasing size of array!" << endl;
        int new_max_size = space_used+1;
        delete [] list;
        int *list_new = new int[new_max_size];

        for(int i=0; i<new_max_size; i++)
        {
            list_new[i] = i;
            cout << list_new[i] << ". ";
        }
        cout << endl;
        space_used++;
        list = list_new;
        return false;
    }
}

You have the right idea, but the implementation could use a little 'elbow-grease' 您有正确的想法,但实施过程中可能会使用一些“手肘油脂”

try this: 尝试这个:

keep 2 int 保持2 int

capacity - length to which you allocate 容量-您分配的长度
size - current end of array 大小-数组的当前结尾

if capacity <= size:
   make new list( size = capacity x 2 )
   memcopy old list into new list -> if you can't memcopy, copy over the data one-by-one
   delete old list
if capacity > size:
   list[size] = value
   size++

http://www.cplusplus.com/reference/clibrary/cstring/memcpy/ http://www.cplusplus.com/reference/clibrary/cstring/memcpy/

One problem that jumps out at me is that you're not changing the value of your list pointer outside of the scope of your list_add function. 让我惊讶的一个问题是,您没有在list_add函数的作用域之外更改列表指针的值。 You should make some changes like... 您应该进行一些更改,例如...

bool list_add(int *list, int& space_used, int max_size, int value)

becomes 变成

bool list_add(int **list, int& space_used, int max_size, int value)

and

list = list_new

becomes 变成

*list = list_new

Otherwise I think you'll find that when you reallocate your list, after returning from list_add your list pointer will still point to the old location. 否则,我认为您会发现,当您重新分配列表时,从list_add返回后,列表指针仍将指向旧位置。

There four problems with the implementation of your code: 您的代码的实现存在四个问题:

  1. It doesn't copy the elements of the list. 它不会复制列表的元素。
  2. It doesn't assign the value of new_list to the list variable in main 它并不值分配new_listlist中的变量main
  3. It inserts values from the back to the front, instead of after the last value 它从后到前插入值,而不是最后一个值之后
  4. max_size doesn't get updated. max_size不会更新。 It's easy to miss this, because you only increase the size of the array by one each time. 很容易错过这一点,因为您每次仅将数组的大小增加一。 That way it would need to allocate each time a value is added. 这样,每次添加值时都需要分配。 If you increase the new size by more then one it will still reallocate every time. 如果将新大小增加一倍,则每次仍将重新分配。

The first problem can be fixed by changing the for loop in list_add so it makes a copy: 第一个问题可以通过更改list_add的for循环来解决,以便进行复制:

for (int i = 0; i < space_used; i++) {   // this also changed.
    list_new[i] = list[i];
    cout ...
}
// insert the new value (in the front?)
list_new[max_size-space_used-1] = value;     
delete [] list;         // Delete the list afterwards instead of earlier.

The second problem can by fixed by returning a pointer to the list. 第二个问题可以通过返回指向列表的指针来解决。 Change the main function to this: main功能更改为此:

for (int i = 0; i < 11; i++) {
    list = list_add(list, used, N, i); 
} 

The third problem can be fixed by changing this line 第三个问题可以通过更改此行来解决

list_new[max_size-space_used-1] = value;

to

list_new[space_used++] = value;

You should also remove the space_used++ after this. 您还应该在此之后删除space_used++

To see the fourth problem you should change this line 要查看第四个问题,您应该更改此行

int new_max_size = space_used+1;

to

int new_max_size = space_used+3;

It will still reallocate every time. 每次仍将重新分配。 It should however reallocate only two times. 但是,它应该只重新分配两次。


This is the full code: 这是完整的代码:

#include <iostream>
using std::cout;
using std::endl;

int* list_add(int *list, int& space_used, int& max_size, int value) {
    if (max_size - space_used > 0) {
        list[space_used++] = value;
        return list;
    }
    else {
        cout << "Increasing size of array!" << endl;
        int new_max_size = space_used+1;

        int *list_new = new int[new_max_size];

        for (int i = 0; i < space_used; i++) {
            list_new[i] = list[i];
            cout << list_new[i] << ". ";
        }
        cout << endl;

        list_new[space_used++] = value;
        max_size=new_max_size;

        delete [] list;
        return list_new;
    }
}

int main() {
    int N = 7;

    //declaring dynamic array allocation
    int* list = new int[N];

    int used = 0, a_val;

    for (int i = 0; i < 11; i++) {
        list=list_add(list, used, N, i);
    }

    cout << endl << "Storlek: " << N << endl << endl;
    cout << "Printar listan " << endl;

    for (int i = 0; i < used; i++) {
        cout << list[i] << ". ";
    }
}

I would worry about this line: 我会担心这一行:

*(list+(max_size-space_used-1)) = value;

and this one: 还有这个:

list_new[i] = i;

There is a lot to be said for knowing how to solve problems, but this isn't one of them. 要知道如何解决问题,有很多话要说,但这不是其中之一。

#include <vector>
#include <iostream>

int main() 
{
    std::vector<int> numbers;

    for (int i = 0; i < 11; i++) {
        numbers.push_back(i);
    }

    for (int i = 0; i < numbers.size(); i++) {
        std::cout << numbers[i] << ". ";
    }

    std::cout << "\n";
}

UPDATE : As shown above in my other answer his function contains at least four bugs in 16 lines. 更新 :如上我的另一个答案所示,他的函数在16行中包含至少四个bug。 That is a bug for every four lines of code. 这是每四行代码的错误。 And then there are the problems with the design of the code. 然后是代码设计的问题。 For example the size of the array and the array itself should be together. 例如,数组的大小和数组本身应该在一起。 You can't otherwise guarantee that the function works. 否则,您不能保证该功能正常运行。

Two of the problems in the code (2,4) could be solved by using a struct containing the array pointer and the max_size of the data structure. 通过使用包含数组指针和数据结构的max_size的struct ,可以解决代码(2,4)中的两个问题。 That way you have to pass the two variables together. 这样,您必须将两个变量一起传递。

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

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