samedi 12 août 2017

Template string parser returning vector C++11

I am trying to write a string parser that will work potentially on strings/doubles/ints/floats. I can use C++11 but not boost. I have got it working (below), and had two questions:

1) Am I missing some additional features of C++11 that will make it easier.

template<typename ReturnType>
    std::vector<ReturnType> Parse(
         const std::string& inputString,
         std::string delimiter) {

size_t start = 0;
size_t end = inputString.find_first_of(delimiter);
std::vector<ReturnType> return_vector;

while (end <= std::string::npos)
{
    // Trying to initialize to ReturnType's default value
    ReturnType temp_return;
    // Using stringstream to convert to ReturnType since it will work on
    // strings/doubles/ints/floats

    // If start and end are equal it means there is a blank entry, for example
    // something like 1,2,3,,4,5 (note the double ,,)
    if (start != end) {
        std::stringstream(inputString.substr(start, end - start)) >> temp_return;
    }
    else {
        // empty or no value 
        std::stringstream("0") >> temp_return;
    }
    return_vector.emplace_back(temp_return);
    if (end == std::string::npos) {
        break;
    }

    start = end + 1;
    end = inputString.find_first_of(delimiter, start);
}

    return return_vector;
}

2) Not completely related but is it possible to implement the parser in two different formats, above code and below. Where returnVector is initialized somewhere else, or already defined and the parser inserts elements, calling vector.at(index)

 template<typename ReturnType>
Parse(
     const std::string& inputString,
     std::string delimiter,
     std::vector<ReturnType> returnVector )

Aucun commentaire:

Enregistrer un commentaire