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.
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));
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With