gpt4 book ai didi

c++ - 如何在不复制或查找的情况下获得 const stringstream 缓冲区的长度?

转载 作者:IT老高 更新时间:2023-10-28 23:20:56 36 4
gpt4 key购买 nike

我有一个 const std::stringstream并希望找出其底层字符串缓冲区中有多少字节。

  • 我不能seekg到最后,tellg然后 seekg重新开始,因为这些操作都不可用const

  • 我不想得到 str().size()因为str()返回一个拷贝,这可能不是一个微不足道的数据量。

我有什么好的选择吗?


(流本身以 const 的形式呈现给我,只是因为它是另一种类型的成员,并且我收到了对该类型对象的 const 引用。流表示一个“文档”,它的封装对象代表一个 CGI 响应,我正在尝试从 Content-Length 中生成准确的 operator<<(std::ostream&, const cgi_response&) HTTP header 行。)

最佳答案

我从来都不习惯使用流缓冲区,但是 this seems to work for me :

#include <iostream>
#include <sstream>

std::stringstream::pos_type size_of_stream(const std::stringstream& ss)
{
std::streambuf* buf = ss.rdbuf();

// Get the current position so we can restore it later
std::stringstream::pos_type original = buf->pubseekoff(0, ss.cur, ss.out);

// Seek to end and get the position
std::stringstream::pos_type end = buf->pubseekoff(0, ss.end, ss.out);

// Restore the position
buf->pubseekpos(original, ss.out);

return end;
}

int main()
{
std::stringstream ss;

ss << "Hello";
ss << ' ';
ss << "World";
ss << 42;

std::cout << size_of_stream(ss) << std::endl;

// Make sure the output string is still the same
ss << "\nnew line";
std::cout << ss.str() << std::endl;

std::string str;
ss >> str;
std::cout << str << std::endl;
}

关键是 rdbuf()const 但返回一个非常量缓冲区,然后可以使用该缓冲区进行查找。

关于c++ - 如何在不复制或查找的情况下获得 const stringstream 缓冲区的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27428736/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com