C ++动态数据 - 如何获取它以及如何摆脱它

问题描述 投票:0回答:2

下面的代码 - 它是一个运行动态数据集的程序的框架。我们的想法是使用包含两个字段的结构:第一个存储集合中的元素数量,第二个是实际集合(动态分配的int向量)。如您所见,该集合中填充了所需数量的伪随机数据。不幸的是,该计划需要完成,这是最重要的功能。

这是我对该功能的期望:

  1. 如果集合为空,则应分配单元素向量并在其中存储新值。
  2. 如果集合不为空,它应该分配一个长度比当前向量大1的新向量,然后将旧向量中的所有元素复制到新向量,将新值附加到新向量,最后释放旧矢量。 #include <iostream> #include <cstdlib> #include <ctime> using namespace std; struct Collection { int elno; int *elements; }; void AddToCollection(Collection &col, int element) { //the first part of the funtion if (col.elno==0){ col.elements= new int[1]; col.elements[0]= element; } //this is the second part but i do not know how to do it. //Please help me to complete*************** else { int *temp; temp = new[]; } } void PrintCollection(Collection col) { cout << "[ "; for(int i = 0; i < col.elno; i++) cout << col.elements[i] << " "; cout << "]" << endl; } int main(void) { Collection collection = { 0, NULL }; int elems; cout << "How many elements? "; cin >> elems; srand(time(NULL)); for(int i = 0; i < elems; i++) AddToCollection(collection, rand() % 100 + 1); PrintCollection(collection); delete[] collection.elements; return 0; }
c++ vector struct dynamic-arrays dynamic-data
2个回答
1
投票

vector container最初是动态容器。所以你可以使用矢量。

只需在结构中声明向量变量并在AddToCollection函数中使用它。

struct Collection {
    int elno;
    std::vector<int> elements;
};
void AddToCollection(Collection &col, int element) {
    col.elements.push_back(element);
    col.elno++;
}

像这样。


0
投票

这是你在找什么:

void AddToCollection(Collection &col, int element)
{
    if(col.elements == NULL)
    {
        col.elements = new int[1];
        col.elements[0] = element;
        col.elno = 1;
    }
    else
    {
        int *newArr = new int[col.elno+1];
        for(int i = 0; i < col.elno; i++)
        {
            newArr[i] = col.elements[i];
        }
        newArr[col.elno] = element;

        delete[] col.elements;
        col.elements = new int[col.elno+1];
        for(int i = 0; i < col.elno+1; i++)
        {
            col.elements[i] = newArr[i];
        }

        delete[] newArr;
        newArr = NULL; // avoid dangling pointer
        col.elno++;
    }
}

肯定使用矢量容器是一个很好的想法,但练习不需要修改主要功能。本练习的目的是帮助学生理解动态分配的内存。

© www.soinside.com 2019 - 2024. All rights reserved.