我有一个111;222;333要转换为三个整数的字符串。
首先我将字符串分割
std::vector<std::string> split(...){ ... };
Run Code Online (Sandbox Code Playgroud)
返回值vector以推导类型存储
std::vector splitVals {split(...)};
Run Code Online (Sandbox Code Playgroud)
如果我想将值转换为整数,就像这样
int foo1 {std::stoi(splitVals[0])};
Run Code Online (Sandbox Code Playgroud)
该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])};
Run Code Online (Sandbox Code Playgroud)
std::stoi现在可以工作了,因为输入值为std::string。问题似乎始于从返回的函数初始化向量std::vector<std::string>。没有这些限制,是否有办法从C ++ 17类模板参数推导中受益?
不要使用大括号初始化。它偏向于std::initializer_list构造函数,因此可以推导出向量作为元素的子向量。使用括号应将其清除。
std::vector splitVals (split(...));
Run Code Online (Sandbox Code Playgroud)
现在,推荐使用复制推导指南,并且向量推导的类型应推导为std::string。