问题描述
目前,我从 std :: ostringstream
设置 std :: vector< char>
的值,如下所示:
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());
}
我想知道是否有更有效的方法可以使用C ++中的STL来执行此操作,或者我在此给出的方法是否合适?我会改用 std :: stringstream
更好吗?
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?
推荐答案
您的方法调用未定义的行为. stream.str()
返回一个字符串 by-value ,也就是一个临时字符串.您使用一个临时对象的 begin
迭代器,以及另一个临时对象的 end
迭代器,创建一个无效范围.
Your method invokes undefined behaviour. stream.str()
returns a string by-value, aka a temporary string. You take the begin
iterator of one temporary and the end
iterator of the other, creating an invalid range.
将流转换为容器的一种方法是使用通用的迭代器接口:
One method to convert a stream to a container is to use the common iterator interface:
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>
int main(){
std::stringstream src("....");
std::vector<char> dest;
// for a bit of efficiency
std::streampos beg = src.tellg();
src.seekg(0, std::ios_base::end);
std::streampos end = src.tellg();
src.seekg(0, std::ios_base::beg);
dest.reserve(end - beg);
dest.assign(std::istreambuf_iterator<char>(src), std::istreambuf_iterator<char>());
std::copy(dest.begin(), dest.end(), std::ostream_iterator<char>(std::cout));
}
另一种方法是缓存返回的 std :: string
对象:
Another method would be to cache the returned std::string
object:
std::string const& s = stream.str();
data.reserve(s.size());
data.assign(s.begin(), s.end());
这篇关于有没有更有效的方法来从流中设置std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!