How to make generic stringToVector function in c++?

时间:2019-04-23 15:06:45

标签: c++ generics vector

I am trying to make a generic stringToVector function.

The input is a string that contains multiple int or string separated by comma (let's ignore char)

ex) [1, 5, 7] or [conver, to, string, vector]

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.

1 个答案:

答案 0 :(得分:3)

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.