繁体   English   中英

转换矢量的最佳方法是什么<vector<string> &gt; 进入向量<vector<double> &gt;? </vector<double></vector<string>

[英]What is the best way to convert vector<vector<string>> into vector<vector<double>>?

以下是示例。

vector<vector<string>> vec_str = {{"123", "2015", "18"}, {"345", "2016", "19"}, {"678", "2018", "20"}};
vector<vector<double>> vec_dou;

我想将 vec_str 转换为 {{123, 2015, 18}, {345, 2016, 19}, {678, 2018, 20}}。 我尝试使用 std::transform 方法,但是当我在 for 循环或 while 循环中使用 transform 时,它不能正常工作,这意味着它返回了错误代码 03。

[Thread 11584.0x39f4 exited with code 3]
[Thread 11584.0x5218 exited with code 3]
[Inferior 1 (process 11584) exited with code 03]

我不知道错误的确切原因,所以请不要问我.. VS 代码只返回了上述错误。 ;-(

最好的方法是什么?

您可以使用嵌套的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;
    }
}

这是一个非常简单的方法:

#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';
    }
}

output:

 123 2015 18
 345 2016 19
 678 2018 20

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM