Assign a std::vector to a std::valarray

user1434698 picture user1434698 · Nov 29, 2012 · Viewed 8.3k times · Source

I have a vector<vector<double>, so a table (matrix) of values. Columns contains position and velocity of a planet, so rows stores data of the same planet. I want to transform a row in a valarray because I need math operations. Then I want to store the valarrays (the planets) in a vector. I tried like this:

vector<vector<double>> corps_tmp=configFile.get_corps(); // The function returns a vector<vector<double>>

    valarray<double> corpX;
    for (int i(0); i < corps_tmp.size(); i++) {
        corpX = corps_tmp[i]; // I want to save the first row of the vector<vector<double>> on the valarray
        corps.push_back(corpX); // I want to ''add'' the valarray to a vector.
        corpX = 0;
    }

This code doesn't works and I obtain an error around the assignment of a vector to a valarray (apparently not permitted).

Is there any way to achieve in a simple way what I tried to do?

Answer

ecatmur picture ecatmur · Nov 29, 2012

To create a valarray from a vector:

std::valarray<double> corpX(corps_tmp[i].data(), corps_tmp[i].size());

To write the data back into a vector:

corps_tmp[i].assign(std::begin(corpX), std::end(corpX));