c++ - 如何让 istringstream 更加高效?

标签 c++ performance standards c++17

#include <sstream>

using namespace std;

const char* GetHugeString();

int main()
{
    const char* p = GetHugeString();

    //
    // Below will copy the huge string into a std::string object!
    // 
    istringstream sstrm{p}; 

    return {};
}

istringstream不需要庞大字符串的拷贝;一个以 null 结尾的字符串指针就足够了。但是istringstreamctor只取std::string ,而不是 std::string_view (仅限 c++1z)作为其参数。

有没有解决方法可以使std::istringstream在这种情况下效率更高吗?

最佳答案

您可以简单地分配istringstream内部使用的缓冲区:

istringstream stream;
stream.rdbuf()->pubsetbuf(p, strlen(p));

这不会复制字符串。请注意pubsetbuf()想要 char* 而不是 const char*,但它实际上不会修改字符串,因此您可以在传递 C 字符串指针之前对其进行 const_cast .

关于c++ - 如何让 istringstream 更加高效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41009325/

相关文章:

C++如何泛化类函数参数来处理多种类型的函数指针?

c++ - 上传输入时出现 SIGSEGV 错误

android - Opengl es 2.0 自定义着色器低 fps (android)

performance - Nuget Pack 性能低下

xml - xbrl us gaap contextRef 标准?

更改 const 原语仅生成警告

c++ - 在 Python 中公开 C++ 单例

c++ - 实现接口(interface)类的纯虚方法的方法也应该声明为虚方法吗?

php - 使用 mysqli 时禁用 BEGIN/COMMIT

c# - 有没有一种方法可以跨不同语言标准化 Windows 事件日志查询?