c++ - 如何动态调整数组的大小?

标签 c++ arrays dynamic resize

我试图将未知数量的元素读入数组,当我的大小达到当前容量时,我调用一个函数将大小加倍并将旧数组的内容复制到新数组中。我得到了“&”,但它似乎仍在按值传递数组。

#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/

相关文章:

c++ - 计算机生成随机数的猜谜游戏

c++ - 如何制作仅屏蔽 32 位的某些部分(索引)的位掩码?

c++ - 计算c++中操作之间的时间长度

C++ - 增加二维字符串 vector 中外部 vector 的大小

angular - 在 Handsontable Cells 中渲染 Angular 组件

c++ - QTabBar 选项卡的内部 QWidgets?

C - 为什么我不断打印内存地址而不是数组中的值

python - 如何切片 2D numpy 数组以获得它的直接邻居?

javascript - 如何设置加载动态内容的 onClick 属性?

javascript - 通过动态 XML+XSL 的 SVG