samedi 28 janvier 2017

the efficient way to initialize a vector with std::regex_token_iterator

I wrote a simple split function to myself. It consists three version. All three version work well. But one of them uses index in positive and negative form.

Here is the complete code:

struct Split {
    std::vector< std::string > operator()
    ( std::string string, const std::string& user_token , long index, long length ){

    std::basic_regex< char > token( user_token );
    std::vector< std::string > result;

    std::regex_token_iterator< std::string::iterator > first( string.begin(), string.end(), token, -1 );
    std::regex_token_iterator< std::string::iterator > last;

    // if the index would be negative
    // find the correct index for first while
    const std::ptrdiff_t distance =  std::distance( first, last );
    if( index < 0 ){
        index += distance;
        index -= ( length - 1 );
    }

    // go ahead until the user-apply-index
    while( index-- ) first++;

    // push back until length == 0
    while( length ){
        result.emplace_back( *first );
        ++first;
        --length;
    }

    return result;
} split;

I am a little worried with using vector.emplace_pack

Here:

while( length ){
    result.emplace_back( *first );
    ++first;
    --length;
}

Here is the test:

std::string string( "one two three four five six seven eight nine ten" );

/// forward: ( from begin to end )
for( int index = 0; index < 2; ++index )
    std::cout << split( string, " ", 0, 2 )[ index ] << ' ';        // okay: one two

puts( "" );
for( int index = 0; index < 2; ++index )
    std::cout << split( string, " ", 2, 2 )[ index ] << ' ';        // okay: three four

puts( "" );
for( int index = 0; index < 2; ++index )
    std::cout << split( string, " ", 8, 2 )[ index ] << ' ';        // okay: nine ten


/// backward: ( from end to begin )
puts( "" );
for( int index = 0; index < 3; ++index )
    std::cout << split( string, " ", -1, 3 )[ index ] << ' ';       // okay: eight nine ten

puts( "" );
for( int index = 0; index < 3; ++index )
    std::cout << split( string, " ", -3, 3 )[ index ] << ' ';       // okay: six seven eight

puts( "" );
for( int index = 0; index < 3; ++index )
    std::cout << split( string, " ", -8, 3 )[ index ] << ' ';       // okay: one two three

Is there any good way to initialize the vector?

Aucun commentaire:

Enregistrer un commentaire