Presently, I set the value of a std::vector<char>
from an std::ostringstream
as follows:
void
foo(std::vector<char> &data, std::stringstream &stream) {
data = std::vector<char>(stream.str().begin(), stream.str().end());
}
I'm wondering if there is a more efficient way to do this with STL in C++ or whether the method I give here is considered appropriate? Would I be better off using std::stringstream
instead?
Your method invokes undefined behaviour.
stream.str()
returns a string by-value, aka a temporary string. You take thebegin
iterator of one temporary and theend
iterator of the other, creating an invalid range.One method to convert a stream to a container is to use the common iterator interface:
Live example on Ideone.
Another method would be to cache the returned
std::string
object: