First of all. There are one million solutions for your problem. Everbody can use what he wants. Styles are different. Newbies generally like C-Style solutions more than sophisticated and "modern C++" solution.
Im my very humble opinion, (only my personal opinion) the answer from user "super" (+1) is by far better as the accepted answer from user "selbie". But OP accepted it and hence, it is the most fitting answer for OP.
I would like to show an additional solution, which is the same as from user "super", just using "more-modern" C++ elements.
You have a 2 dimensional std::vector
. That is a very good approach. Now you want to transform this std::vector
of std::vector
of std::string
into a different data type. You even used the tag "transform" in your question.
For such transformation, you could use a function from the C++ library that has been made for excactly this purpose. It is called std::transform
.
It transforms elements from a container into something different. It iterates over each element in a container and then uses a "function", e.g a lambda, to transform that element.
With 2 dimensional vectors, we need to apply std::transform
for each dimension.
And because such a dedicated function is existing in C++, I would recommend to use it.
See the below example:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
int main() {
// The source data
std::vector<std::vector<std::string>> vvs{ {"1","2","3","4"},{"5","6","7","8"},{"9","10","11","12"},{"13","14","15","16"}};
// Here we will store the result
std::vector<std::vector<double>> vvd{};
// Transform 2 dimensional vector
// Outer vector
std::transform(vvs.begin(), vvs.end(), std::back_inserter(vvd), [](const std::vector<std::string>&vs) {
std::vector<double> vd{};
// Inner vector
std::transform(vs.begin(), vs.end(), std::back_inserter(vd), [](const std::string& s) { return std::stod(s); });
return vd;
});
// Show debug output
std::for_each(vvd.begin(), vvd.end(), [](const std::vector<double>& vd) {
std::copy(vd.begin(), vd.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << "\n"; });
return 0;
}
But, as said, everybody can do, what he wants.