首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将vector<vector<string>>转换为vector<vector<double>>的最佳方法是什么?

将vector<vector<string>>转换为vector<vector<double>>的最佳方法是什么?
EN

Stack Overflow用户
提问于 2021-12-23 07:02:23
回答 2查看 73关注 0票数 -1

下面是一个例子。

代码语言:javascript
复制
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。

代码语言:javascript
复制
[Thread 11584.0x39f4 exited with code 3]
[Thread 11584.0x5218 exited with code 3]
[Inferior 1 (process 11584) exited with code 03]

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

做这件事最好的方法是什么?

EN

回答 2

Stack Overflow用户

发布于 2021-12-23 07:09:10

您可以通过嵌套的std::transform来实现这一点。

螺栓连接

代码语言:javascript
复制
#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;
    }
}
票数 2
EN

Stack Overflow用户

发布于 2021-12-23 09:31:58

下面是一种非常简单的方法:

代码语言:javascript
复制
#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';
    }
}

产出:

代码语言:javascript
复制
 123 2015 18
 345 2016 19
 678 2018 20
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70458719

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档