简体   繁体   English

如何在C ++中使通用的stringToVector函数?

[英]How to make generic stringToVector function in c++?

I am trying to make a generic stringToVector function. 我试图做一个通用的stringToVector函数。

The input is a string that contains multiple int or string separated by comma (let's ignore char) 输入是一个包含多个int或用逗号分隔的字符串的字符串(让我们忽略char)

ex) [1, 5, 7] or [conver, to, string, vector] 例如[1、5、7]或[转换,转换为字符串,向量]

I want a generic function like this 我想要这样的通用功能

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

Is there any way around? 有什么办法吗?

I know this function is dumb, but I just want this for a competitive programming. 我知道这个功能是愚蠢的,但是我只是想要一个有竞争力的程序。

Usually it is done by a helper function: 通常,它是通过一个辅助函数来完成的:

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 );
}

inside your function: 在您的函数内:

str::string str;
while (getline(ss, str, delim))
   output.push_back( my_convert<T>( std::move( str ) ) );

it will fail to compile for any other type than std::string or int but you can add more specializations of my_convert if you need to support other types. 它不能为除std::stringint以外的任何其他类型进行编译,但是如果需要支持其他类型,则可以添加my_convert更多特殊化。

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

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