将字符串移出std :: ostringstream [英] Move the string out of a std::ostringstream
问题描述
如果我使用std::ostringstream
构造由空格分隔的浮点值列表组成的字符串:
If I construct a string made of a list of space separated floating point values using std::ostringstream
:
std::ostringstream ss;
unsigned int s = floatData.size();
for(unsigned int i=0;i<s;i++)
{
ss << floatData[i] << " ";
}
然后我在std::string
中得到结果:
std::string textValues(ss.str());
但是,这将导致不必要的字符串内容深层复制,因为不再使用ss
.
However, this will cause an unnecessary deep copy of the string contents, as ss
will not be used anymore.
是否可以在不复制整个内容的情况下构造字符串?
Is there any way to construct the string without copying the entire content?
推荐答案
std::ostringstream
不提供公共接口来访问其内存中缓冲区,除非它非便携式地支持pubsetbuf
(但即使那样,您的缓冲区也是固定大小的) ,请参见 cppreference示例)
std::ostringstream
offers no public interface to access its in-memory buffer unless it non-portably supports pubsetbuf
(but even then your buffer is fixed-size, see cppreference example)
如果要折磨某些字符串流,可以使用受保护的接口访问缓冲区:
If you want to torture some string streams, you could access the buffer using the protected interface:
#include <iostream>
#include <sstream>
#include <vector>
struct my_stringbuf : std::stringbuf {
const char* my_str() const { return pbase(); } // pptr might be useful too
};
int main()
{
std::vector<float> v = {1.1, -3.4, 1/7.0};
my_stringbuf buf;
std::ostream ss(&buf);
for(unsigned int i=0; i < v.size(); ++i)
ss << v[i] << ' ';
ss << std::ends;
std::cout << buf.my_str() << '\n';
}
std::ostrstream
提供了直接访问自动调整大小的输出流缓冲区的标准C ++方法,在c ++ 98中已弃用,但在标准c ++ 14中仍在计数.
The standard C++ way of directly accessing an auto-resizing output stream buffer is offered by std::ostrstream
, deprecated in C++98, but still standard C++14 and counting.
#include <iostream>
#include <strstream>
#include <vector>
int main()
{
std::vector<float> v = {1.1, -3.4, 1/7.0};
std::ostrstream ss;
for(unsigned int i=0; i < v.size(); ++i)
ss << v[i] << ' ';
ss << std::ends;
const char* buffer = ss.str(); // direct access!
std::cout << buffer << '\n';
ss.freeze(false); // abomination
}
However, I think the cleanest (and the fastest) solution is boost.karma
#include <iostream>
#include <string>
#include <vector>
#include <boost/spirit/include/karma.hpp>
namespace karma = boost::spirit::karma;
int main()
{
std::vector<float> v = {1.1, -3.4, 1/7.0};
std::string s;
karma::generate(back_inserter(s), karma::double_ % ' ', v);
std::cout << s << '\n'; // here's your string
}
这篇关于将字符串移出std :: ostringstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!