动态数组 [英] Dynamic Arrays

查看:108
本文介绍了动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习C ++,所以请原谅我这个简单的问题。我正在做的是从一个文件中读取数字,然后尝试将它们添加到数组。我的问题是如何增加数组的大小?例如我认为可能能够做:

I'm just starting to learn C++ so excuse me for this simple question. What I'm doing is reading in numbers from a file and then trying to add them to an array. My problem is how do you increase the size of the array? For example I thought might be able to just do:

#include <iostream>
using namespace std;

int main() {
    double *x;
    x = new double[1];
    x[0]=5;
    x = new double[1];
    x[1]=6;
    cout << x[0] << "," << x[1] << endl;
    return 0;
}

但这显然只是覆盖了我最初设置为x的值5 [0],所以输出0,6。我将如何让它输出5,6?

请认识到,对于我包括的例子,我不想把它与从文件或代码读取杂乱从用户获取数字。在实际应用中,我不知道在编译时需要一个数组的大小,所以请不要告诉我只要做一个数组有两个元素,并设置它们分别为5和6.

感谢您的帮助。

But this obviously just overwrites the value, 5, that I initially set to x[0] and so outputs 0,6. How would I make it so that it would output 5,6?

Please realize that for the example I've included I didn't want to clutter it up with the code reading from a file or code to get numbers from a user. In the actual application I won't know how big of an array I need at compile time so please don't tell me to just make an array with two elements and set them equal to 5 and 6 respectively.

Thanks for your help.

推荐答案

您不想直接使用数组。请考虑使用向量。然后,你可以调用 push_back 函数来添加东西到最后,它会自动为你调整向量大小。

You don't want to work with arrays directly. Consider using a vector, instead. Then, you can call the push_back function to add things to the end, and it will automatically resize the vector for you.

#include <iostream>
#include <vector>

int
main() {
    double value;
    std::vector<double> values;

    // Read in values
    while (std::cin >> value) {
        values.push_back(value);
    }

    // Print them back out
    for (std::size_t i(0), len(values.size()); i != len; ++i) {
        std::cout << values[i];
    }
}

这篇关于动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆