std :: stringstream与std :: string串联多个字符串 [英] std::stringstream vs std::string for concatenating many strings

查看:97
本文介绍了std :: stringstream与std :: string串联多个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 std :: stringstream 的优点之一是它是 std :: istream ,因此它可以接受来自定义的任何类型的输入运算符<< std :: istream ,也来自原始类型.

I know one of the advantages of std::stringstream is that it is a std::istream so it may accept input from any type that defines operator<< to std::istream, and also from primitives types.

我将不使用 operator<< ;相反,我只是要连接许多字符串. std :: stringstream 的实现是否比连接许多字符串的 std :: string 更快?

I am not going to use operator<<; instead I am just going to concatenate many strings. Does the implementation of std::stringstream make it faster than std::string for concatenating many strings?

推荐答案

没有理由期望 std :: string 的附加函数比 stringstream '慢的插入功能. std :: string 通常只不过是可能的内存分配/复制以及将数据复制到内存中.即使对于基本的 write 调用, stringstream 也必须处理语言环境等问题.

There's no reason to expect std::string's appending functions to be slower than stringstream's insertion functions. std::string will generally be nothing more than a possible memory allocation/copy plus copying of the data into the memory. stringstream has to deal with things like locales, etc, even for basic write calls.

此外, std :: string 提供了最小化或消除除第一次内存分配以外的任何方法的方法.如果您保留足够的空间,则每次插入只不过是 memcpy .对于 stringstream ,这实际上是不可能的.

Also, std::string provides ways to minimize or eliminate anything but the first memory allocation. If you reserve sufficient space, every insertion is little more than a memcpy. That's not really possible with stringstream.

即使它比 std :: string 的附加函数要快,您仍然必须将字符串从 stringstream 中复制出来用它做点事.这是另一个分配+副本,您无需使用 std :: string .尽管至少C ++ 20似乎可以消除这种特殊需求.

Even if it were faster than std::string's appending functions, you still have to copy the string out of the stringstream to do something with it. So that's another allocation + copy, which you won't need with std::string. Though at least C++20 looks set to remove that particular need.

如果您需要 formatting 格式,则应该使用 std :: stringstream ,而不仅仅是将一些字符串粘贴在一起.

You should use std::stringstream if you need formatting, not just for sticking some strings together.

这篇关于std :: stringstream与std :: string串联多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆