Using operator[] on empty std::vector

前端 未结 7 991
迷失自我
迷失自我 2021-01-12 05:29

I was advised a while ago that is was common place to use std::vector as exception safe dynamic array in c++ rather than allocating raw arrays... for exampl

7条回答
  •  甜味超标
    2021-01-12 06:23

    This brought an interesting question to my mind, which I promptly asked here. In your case, you can avoid using pointers the following way:

    template
    OutputIterator copy_n( InputIterator first, InputIterator last, OutputIterator result, std::size_t n)
    {
        for ( std::size_t i = 0; i < n; i++ ) {
            if (first == last)
                break;
            else
                *result++ = *first++;
        }
        return result;
    }
    
    std::ifstream file("path_to_file");
    std::vector buffer(n);
    copy_n(std::istream_iterator(file), 
           std::istream_iterator(),
           std::back_insert_iterator >(buffer),
           n);
    

    This will copy the contents of the file to a buffer n chars at a time. When you iterate over the buffer, use:

    for (std::vector::iterator it = buffer.begin(); it != buffer.end(); it++)
    

    instead of a counter.

提交回复
热议问题