GLProgramming.com

home :: about :: development guides :: irc :: forums :: search :: paste :: links :: contribute :: code dump

-> Click here to learn how to get live help <-


New Paste :: Recent Pastes:: Add Line Numbers


Please use C whenever possible by glDaher
#include <iostream>    // std::cout
#include <string>    // std::string


template <int _Length = 10, int _Radix = 10> struct fixed_length_string_func
    {    
    inline std::string operator () ( int _Count )
        {
        char buf[_Length + 1];
        ::itoa( _Count, buf, _Radix);
        size_t sz = strlen(buf);
        size_t at = _Length - sz;

        char out[_Length + 1];
        for( size_t i= 0; i< _Length; i++)
            {
            out[i] = i < at ? '0' : buf [ i - at ];
            }
        out[_Length] = '\0';
        return out;
        }
    };

#include <sstream>    // std::ostringstream
template <int _Length = 10, int _Radix = 10> struct fixed_length_string_func2
    {    
    inline std::string operator () ( int _Count )
        {
        std::ostringstream sstr;
        sstr << _Count << std::ends;

        size_t sz = sstr.str().length();
        size_t at = _Length - sz;

        std::string out;
        for( size_t i= 0; i< _Length; i++)
            {
            out += i < at ? '0' : sstr.str() [ i - at ];
            }
        return out;
        }
    };


#include <windows.h>                // for TimeGetTime()
#pragma comment (lib, "winmm.lib")    // for TimeGetTime()

void main()
    {
    const max = 1000000;

        {
        DWORD t = timeGetTime();

        fixed_length_string_func<> get_folder_name;

        for( int i=0; i< max; i++)
            get_folder_name( i );
        
        std::cout << "1st loop time elapsed = " << timeGetTime() - t << std::endl;

        }

        {
        DWORD t = timeGetTime();

        fixed_length_string_func2<> get_folder_name;

        for( int i=0; i< max; i++)
            get_folder_name( i );
        
        std::cout << "2st loop time elapsed = " << timeGetTime() - t << std::endl;
        }
    }