Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 2D vector - Convert int to double

Tags:

c++

vector

What is a good way to convert vector<vector<int>> vint to vector<vector<double>>vdouble?

I know from C++ convert vector<int> to vector<double> that this can be done for 1-D but I am not too sure how to do it for 2-d case.

like image 547
dimsum204 Avatar asked Feb 10 '23 21:02

dimsum204


2 Answers

Here's a pretty simple solution which uses emplace_back and the vector range constructor:

std::vector<std::vector<int>> intvec;
//intvec filled somehow

std::vector<std::vector<double>> doublevec;
doublevec.reserve(intvec.size());
for (auto&& v : intvec) doublevec.emplace_back(std::begin(v), std::end(v));
like image 99
TartanLlama Avatar answered Feb 13 '23 04:02

TartanLlama


#include <iostream>                                                                                                                                                                                                                         
#include <vector>
#include <algorithm>

double castToDouble(int v) {
    return static_cast<double>(v);
}

int main() {
    std::vector<std::vector<int>> intv;
    std::vector<std::vector<double>> doublev;

    std::transform(intv.begin(), intv.end(), std::back_inserter(doublev), [](const std::vector<int> &iv) {
        std::vector<double> dv;
        std::transform(iv.begin(), iv.end(), std::back_inserter(dv), &castToDouble);
        return dv;
    });

    return 0;
}
like image 21
Victor Polevoy Avatar answered Feb 13 '23 04:02

Victor Polevoy