我正在尝试创建一个通用的 stringToVector 函数。
输入是一个字符串,包含多个以逗号分隔的int或字符串(我们忽略char)
例如) [1, 5, 7] 或 [转换、转换为字符串、 vector ]
我想要一个像这样的通用函数
template <class T>
vector<T> stringToVector(string input) {
vector<T> output;
input = input.substr(1, input.length() - 2);
stringstream ss;
ss.str(input);
T item;
char delim = ',';
while (getline(ss, item, delim)) {
if (is_same(T, int)) {
output.push_back(stoi(item)); // error if T is string
} else {
output.push_back(item); // error if T is int
}
}
return output;
}
有什么办法吗?
我知道这个函数很蠢,但我只是想用它来进行竞争性编程。
最佳答案
通常它是由辅助函数完成的:
template<class T>
T my_convert( std::string data );
template<>
std::string my_convert( std::string data )
{
return data;
}
template<>
int my_convert( std::string data )
{
return std::stoi( data );
}
在你的函数中:
str::string str;
while (getline(ss, str, delim))
output.push_back( my_convert<T>( std::move( str ) ) );
它将无法编译除 std::string
或 int
之外的任何其他类型,但您可以添加更多 my_convert
的特化,如果您需要支持其他类型。
关于c++ - 如何在 C++ 中创建通用 stringToVector 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55814206/