由一个函数填充的推断字符串向量转换为整数

3

我有一个字符串 111;222;333,我想将其转换为三个整数。

首先,我将字符串分割:

std::vector<std::string> split(...){ ... };

返回值以推导类型存储在 vector 中。
std::vector splitVals {split(...)};

如果我想将这些值转换为整数,可以像这样:

int foo1 {std::stoi(splitVals[0])};

stoi函数报错了,因为向量的推导类型是std::vector<std::vector<std::string>, std::allocator<std::vector<std::string>>>。但是如果我不让类型被推导,那么一切都能正常工作。

std::vector<std::string> splitVals {split(...)};
int foo1 {std::stoi(splitVals[0])};

std::stoi现在可以工作了,因为输入值是std::string。问题似乎始于向一个返回std::vector<std::string>的函数初始化向量。有没有一种方法可以从C++17类模板参数推断中获益,而没有这些限制?


我的个人建议(超出所给答案):根本不要使用统一初始化,而是优先选择传统的圆括号。虽然UI背后有一个很好的意图,但它的实现方式引入的麻烦比解决的问题还多得多... - Aconcagua
@Aconcagua 不太清楚,我看过一些来自C++标准委员会长期成员Nicolai Josuttis的演讲,他认为这应该是首选的初始化方法(他认为所有剩余的问题在C++20中都已经解决)。 - Croolman
标准委员会的成员们似乎需要支持这些修改。如果问题真的得到解决,那就好了,但我还是有所怀疑。为了解决我的“最爱”问题,必须在使用初始化列表时强制使用双括号(std::vector<int> v{{7, 10, 12}};),但这将破坏向后兼容性。嗯,让我们看看吧。最终,你必须自己做出决定;尽管现在的技术水平已经很高,但我的决定已经定了。 - Aconcagua
2个回答

9
不要使用花括号初始化,因为它偏向于使用 std::initializer_list 构造函数,所以这个向量被推导为包含元素的子向量。使用圆括号可以清楚地解决这个问题。
std::vector splitVals (split(...));

现在推荐使用拷贝推导指南,并且由向量持有的类型应当被推导为std::string


2
"最初的回答"
哇,8个赞和被接受的答案。基本上没有什么可以补充的了...
我只想回到提到的任务本身:
我有一个字符串111;222;333,我想将其转换为三个整数。
这是解析CSV的典型示例。可以使用一行代码(一个语句)轻松完成。使用std :: transform和sregex_toke_iterator。
为了完整起见,我将展示该代码。
#include <iostream>
#include <vector>
#include <string>
#include <regex>
#include <iterator>
#include <algorithm>

int main()
{
    // The test data
    std::string data("111;222;333;444");

    // Here we will see the result
    std::vector<int> values{};

    // This we will look up in the string
    std::regex re("(\\d+)");

    // Put all tokens into vector
    std::transform(
        std::sregex_token_iterator(data.begin(), data.end(), re, 1), 
        std::sregex_token_iterator(),
        std::back_inserter(values),
        [](const std::string& s){ return std::stoi(s); }
    );

    // Show debug output    
    std::copy(values.begin(),values.end(),std::ostream_iterator<int>(std::cout,"\n"));

    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接