简体   繁体   中英

How can I use std::begin and std::end without C++11?

I'm trying to write code that will compile for POJ . POJ doesn't use C++11 so I can't use really basic STL functions like std::to_string , std::begin , or std::end . I looked around and found another StackOverflow question inquiring about std::to_string . To get std::to_string code to compile with a bare g++ myfile.cpp command, a user suggested this patch, which works nicely:

namespace patch
{
    template < typename T > std::string to_string( const T& n )
    {
        std::ostringstream stm ;
        stm << n ;
        return stm.str() ;
    }
}

I want to do the same thing for std::begin , std::end , and std::stoi , but I'm not sure how to do it. I'm quite unfamiliar with the STL. I just want my working C++11 code to compile with either MS-VC++6.0 or G++ without any flags, etc. How can I do this?

Pretty straightforward. For instance, here is std::begin:

template <typename C>
typename C::iterator my_begin(C& ctr) { return ctr.begin(); }

template <typename C>
typename C::const_iterator my_begin(const C& ctr) { return ctr.begin(); }

template <typename C, size_t sz>
C* my_begin(C (&ctr)[sz]) { return &ctr[0]; } 

template <typename C, size_t sz>
const C* my_begin(const C (&ctr)[sz]) { return &ctr[0]; } 

boost::lexical_cast can do the same job as that of to_string and it does not require C++11. Below is a simple example:

std::string s = boost::lexical_cast<std::string>(12345)

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