Dynamic Arrays - How to increase the size of an array?

arrays, c++

Solution

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];
    }
}

Problem

I am 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; } ``` 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.

Original source

Related problems