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

标签 c++ vector struct dynamic-arrays dynamic-data

下面的代码 – 它是对动态数据集合进行操作的程序的骨架。这个想法是使用一个包含两个字段的结构:第一个存储集合中元素的数量,第二个是实际集合(动态分配的整数 vector )。如您所见,集合中充满了所需数量的伪随机数据。 不幸的是,该程序需要完成,这是最重要的功能。

这是我对函数的期望:

  1. 如果集合为空,它应该分配一个单元素 vector 并在其中存储一个新值。
  2. 如果集合不为空,则应分配一个长度比当前 vector 大一的新 vector ,然后将旧 vector 中的所有元素复制到新 vector 中,将新值附加到新 vector 中 vector 并最终释放旧 vector 。

    #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;
    }
    

最佳答案

vector容器本来就是动态容器。所以你可以使用 vector 。

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

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

像这样。

关于C++ 动态数据——如何获取它以及如何摆脱它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48606157/

相关文章:

c++ - undefined symbol boost::system:detail::system_category_instance

c# - 使用舒适的代码为结构上的数组赋值

swift - 如何快速复制一个只有一个不同字段的结构

java - 跨平台和跨语言的客户端/服务器应用程序连接

c++ - 我什么时候想在 visual studio 中关闭 "precompiled header"?

c++ - vulkan 验证层问题

c++ - 共线点 C++

c++ - vector<struct> 上的段错误

c++ - 返回 std::vector 时缺少元素

C++ 结构构造函数错误