简体   繁体   中英

How to make generic stringToVector function in c++?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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