10

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?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • 2
    you should use a plain `std::vector` for your matrix and use some formulas to calculate the proper index. `std::vector>` screws cache. – Stephan Dollberg Nov 29 '12 at 20:59
  • @bamboon I need valarray to create a numerical agorithm that integrates both position and velocity at the same time (so the whole valarray). –  Nov 29 '12 at 21:01

1 Answers1

19

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));
andand
  • 17,134
  • 11
  • 53
  • 79
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • I wasn't aware of `std::begin(std::valarray )` or `std::end(std::valarray )`.Particularly, we have _non-iterator_ arguments when constructing a `std::valarray` from a vector, and _iterator-like_ arguments when assigning to a `std::vector` - in both cases, the expected argument-types are consistent with the type of the object being constructed or assigned to. – damienh Nov 30 '12 at 05:34