下面的代码 – 它是对动态数据集合进行操作的程序的骨架。这个想法是使用一个包含两个字段的结构:第一个存储集合中元素的数量,第二个是实际集合(动态分配的整数 vector )。如您所见,集合中充满了所需数量的伪随机数据。 不幸的是,该程序需要完成,这是最重要的功能。
这是我对函数的期望:
- 如果集合为空,它应该分配一个单元素 vector 并在其中存储一个新值。
如果集合不为空,则应分配一个长度比当前 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/