Is there a more efficient way to set a std::vector from a stream?

前端 未结 4 1771
别那么骄傲
别那么骄傲 2021-01-18 03:37

Presently, I set the value of a std::vector from an std::ostringstream as follows:

void
foo(std::vector &am         


        
4条回答
  •  不知归路
    2021-01-18 04:16

    As pointed out in comments, your code is incorrect due to the two calls to str(). In order to improve efficiency you can avoid creating a temporary vector, like this:

    void foo(std::vector &data, std::stringstream &stream) {
        const std::string& str = stream.str();
        data.assign( str.begin(), str.end() );
    }
    

    You can also avoid the std::string by using std::istreambuf_iterators:

    void foo(std::vector &data, std::stringstream &stream) {
        data.assign(
            std::istreambuf_iterator( stream ), std::istreambuf_iterator()
        );
    }
    

    but given that those are input iterators, the vector has no chance to know how much data will be assigned and could perform a bit worse, as it cannot reserve enough space to avoid reallocations.

提交回复
热议问题