我试图将未知数量的元素读入数组,当我的大小达到当前容量时,我调用一个函数将大小加倍并将旧数组的内容复制到新数组中。我得到了“&”,但它似乎仍在按值传递数组。
#include <iostream>
#include <fstream>
using namespace std;
void resize(int*&, int&);
int main() {
ifstream in("numbers.input");
int cap = 10;
double avg;
int total = 0;
int size = 0;
int *arr = new int [cap];
int temp;
for(int i =0; i <cap; i++){
in >> temp;
if(size >= cap) {
resize(arr,cap);
}
arr[i]=temp;
total += arr[i];
size++;
}
avg = (double) total/cap;
cout << cap <<endl;
cout << size <<endl;
cout << total <<endl;
cout << avg;
return 0;
}
void resize(int *&arr,int &cap) {
cap*=2;
int* newArr = new int[cap];
for(int i = 0; i < cap; i++){
newArr[i] = arr[i];
}
delete [] arr;
arr = newArr;
}
最佳答案
您尝试“手动”实现的所有内容都已经在 标准库。使用 std::vector<> 实现 加倍/重新分配策略与您的策略非常相似 求婚。
#include <fstream>
#include <vector>
int main() {
std::ifstream in("numbers.input");
std::vector<int> arr;
int temp;
while (in >> temp) { arr.push_back(temp); }
// process your data ...
}
参见 http://www.cplusplus.com/reference/vector/vector/
更直白地回答这个问题:数组总是被传递 通过引用,通常是通过传递指向第一个元素的指针。
关于c++ - 如何动态调整数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799856/