#include <iostream>
#include <cctype> // for isdigit function
int main()
{
int initial_size = 10;
int* temp = new int[initial_size];
int actual_size = 0;
while ( 1 )
{
char ch;
cin >> ch;
if ( ch == 'E' )
break;
if ( isdigit(ch) ){
cin.unget();
int n;
cin >> n; //If it's an integer, store it.
actual_size++; // Keep tracks of actual size.
if ( actual_size <= initial_size )
*temp++ = n; //Storing in temp array...
else if ( actual_size > initial_size ){ //When there's not enough space in array..
int old_initial_size = initial_size;
initial_size *= 2; //Doubling the size of initial_size after storing it in old_initial_size.
int* hold = new int[old_initial_size];
for ( int i = 0; i < old_initial_size; i++)
hold[i] = temp[i]; // From temp to hold.This is my attempt at keeping the values of temp array.
temp = new int[initial_size]; // After passing every value in temp i resize it.
for ( int i = 0; i < old_initial_size; i++)
temp[i] = hold[i]; //From hold to newly created temp.
delete[] hold;
}
}
}
int* actualArray = new int[actual_size];
for ( int i = 0; i < actual_size; i++)
actualArray[i] = temp[i];
delete[] temp;
for ( int i = 0; i < actual_size; i++)
cout << actualArray[i] << " ";
}
这是我想要做的事情:
我想一直从用户那里获取输入,直到输入 E 为止。如果输入是整数,我想将其存储在预定义的临时动态数组中,该数组大小为10。
在此过程中,我想计算实际数字输入的数量。如果超过临时数组的初始大小,则希望将临时数组的大小加倍,同时保留其中的旧输入。
当循环终止时,我想将临时数组中的输入传递给我的实际数组,其大小与数字输入完全相同(实际大小)。
您可以看到我的尝试以上面的代码为例。输出结果是随机数字,但至少我得到了正确数量的随机数字。
例如,如果我输入“3 4 E”,我会得到类似于“13123213 1541321231”的东西。
std::vector
。我相信你的代码中至少有一个内存泄漏。 - chris