The below is the example.
vector<vector<string>> vec_str = {{"123", "2015", "18"}, {"345", "2016", "19"}, {"678", "2018", "20"}};
vector<vector<double>> vec_dou;
I want to convert vec_str to {{123, 2015, 18}, {345, 2016, 19}, {678, 2018, 20}}. I try to use std::transform method, but when I use transform in for loop or while loop, it did not work well, that means it returned error code 03.
[Thread 11584.0x39f4 exited with code 3]
[Thread 11584.0x5218 exited with code 3]
[Inferior 1 (process 11584) exited with code 03]
I don't know the exact reason for error, so please don't ask me for that.. VS code only returned the above error. ;-(
What is the best way for this?
CodePudding user response:
You can achieve this with a nested std::transform
:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
vector<vector<string>> vec_str = {{"123", "2015", "18"}, {"345", "2016", "19"}, {"678", "2018", "20"}};
vector<vector<double>> vec_dou;
std::transform(vec_str.begin(), vec_str.end(), std::back_inserter(vec_dou), [](const auto& strs) {
vector<double> result;
std::transform(strs.begin(), strs.end(), std::back_inserter(result), [](const auto& str) { return std::stod(str); });
return result;
});
for (const auto& nums : vec_dou) {
for (double d : nums) {
cout << ' ' << d;
}
cout << endl;
}
}
CodePudding user response:
Here is a very simple way of doing it:
#include <iostream>
#include <string>
#include <vector>
int main( )
{
std::vector< std::vector<std::string> > vec_str = { {"123", "2015", "18"},
{"345", "2016", "19"},
{"678", "2018", "20"} };
// construct vec_dou at exactly the dimensions of vec_str
std::vector< std::vector<double> >
vec_dou( vec_str.size( ), std::vector<double>( vec_str[0].size( ) ) );
for ( std::size_t row = 0; row < vec_str.size( ); row )
{
for ( std::size_t col = 0; col < vec_str[0].size( ); col )
{
vec_dou[row][col] = std::stod( vec_str[row][col] ); // convert each
} // string to double
}
for ( const auto& doubleNumbers : vec_dou ) // print the double numbers
{
for ( const double& num : doubleNumbers )
{
std::cout << ' ' << num;
}
std::cout << '\n';
}
}
The output:
123 2015 18
345 2016 19
678 2018 20