Wednesday, July 9, 2014

Simulate C++11 std::copy_n () function

Let's say you are using a compiler that doesn't have C++11 features on it. Here is a way to simulate std::copy_n (). I believe my implementation is correct.

Tested with Visual Studio 2008 and Visual Studio 2012 (Yes, I know VS2012 has std::copy_n)

    // Simulate C++11 std::copy_n
    template <class InputIterator, class Size, class OutputIterator>
    OutputIterator copy_n (InputIterator first, Size count, OutputIterator result)
    {
        if (count > 0) {
            for (Size n = 0; n < count - 1; ++n, ++first, ++result) {
                        *result = *first ;
            }
           
            *result = *first ; // We don't want to advance `first` again.
            ++result ; // `result` points to one past the last value.
        }

        return result ;
    }

No comments:

Post a Comment