How to extract one row of a 2D string vector to vector of double?

I have a function to calculate moving average:

void MovingAverage(double inputSeries[]
                 , size_t inputSize, size_t window, float* output ) 

My train of thought to do my calculation:

  1. construct a loop and extract one row of vec2D each time
  2. use the MovingAverage function to get output

For the first step, the 2d-vector is parsed from a csv file:

std::vector<std::vector<std::string>> vec2D{
    {"S0001","01","02","03"}, {"S0002","11","12","13"}, {"S0003","21","22","23"}
};

I want to extract one row of this 2D vector (say the 2nd) and store the row as a 1d vector std::vector<double> copyRow then calculate the moving average for each row.

copyRow = {11,12,13}

I tried vector<double> copyRow(vec2D[0].begin(), vec2D[0].end()); but it doesn’t work because the 2D vector is std::string type.

I also tried for loops:

int rowN = vec2D.size();
int colN = vec2D[0].size();
double num;
for (int i = 0; i < rowN; i++) 
{
    for (int j = 0; j < colN; j++) 
    {
        num = stod(vec2D[i][j]);
        copyRow[i][j].push_back(num);
    }
}

But it appends all values from all rows into the vector. What would be the best way to do this?

Answer

I tried vector<double> copyRow(vec2D[0].begin(), vec2D[0].end()); but it doesn’t work because the 2D vector is string type.

You can make use of the algorithm function std::transform from <algorithm> to do this.

Since the first element of each row cannot be transformed to a double , you can skip it by starting from one element after begin iterator:

 #include <algorithm> // std::transform

std::vector<double> copyRow;
// reserve memory for unwanted real locations
copyRow.reserve(vec2D[1].size() - 1u);

std::transform(std::cbegin(vec2D[1]) + 1, std::cend(vec2D[1])
    , std::back_inserter(copyRow), [](const auto& ele) {
        return std::stod(ele);
    });

(See a Demo)