Tuesday, March 1, 2011

How to efficiently copy istringstream?

Or ostringstream?

istringstream a("asd");
istringstream b = a; // This does not work.

I guess memcpy won't work either.

From stackoverflow
  • You can't just copy streams, you have to copy their buffers using iterators. For example:

    #include <sstream>
    #include <algorithm>
    ......
    std::stringstream first, second;
    .....
    std::istreambuf_iterator<char> begf(first), endf;
    std::ostreambuf_iterator<char> begs(second);
    std::copy(begf, endf, begs);
    
    Łukasz Lew : Isn't copying one character at a time slow?
    AraK : Have you measured it?
    Łukasz Lew : I measured it when input was a file ifstringstream. The difference was tremendous.
    AraK : There is nothing called ifstringstream in C++. Could you post the code you wrote?
    AraK : Why would you copy the contents of fstream into stringstream?
  • istringstream a("asd");
    istringstream b(a.str());
    

    Edit: Based on your comment to the other reply, it sounds like you may also want to copy the entire contents of an fstream into a strinstream. You don't want/have to do that one character at a time either (and you're right -- that usually is pretty slow).

    // create fstream to read from
    std::ifstream input("whatever");
    
    // create stringstream to read the data into
    std::istringstream buffer;
    
    // read the whole fstream into the stringstream:
    buffer << input.rdbuf();
    
    AraK : +1 I didn't know there is an overloading for buffers!
    Jerry Coffin : Yeah, it's one of those cute little tricks that almost nobody knows about. Not useful all that often, but when you want what it does, it makes things quite a bit simpler.
    Allen George : Shouldn't that be `ostringstream` instead of `istringstream`?

0 comments:

Post a Comment