You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何不复制内存打印std::string的部分内容?

高效打印字符串首个单词的方案

要避免临时字符串分配带来的性能开销,直接用std::cout::write是最简洁高效的方式,不需要额外构造对象:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string line = "Hello Hello";
    const auto space_iter = std::find(line.cbegin(), line.cend(), ' ');
    std::cout.write(line.data(), space_iter - line.cbegin()) << '\n';
    return 0;
}

如果想用std::span,可以借助它的data()和size()成员,同样通过write输出,避免重载运算符的麻烦:

#include <iostream>
#include <string>
#include <algorithm>
#include <span>

int main() {
    std::string line = "Hello Hello";
    const auto space_iter = std::find(line.cbegin(), line.cend(), ' ');
    std::span<const char> word(line.cbegin(), space_iter);
    std::cout.write(word.data(), word.size()) << '\n';
    return 0;
}

两种方式都不会产生额外的内存分配与复制操作,适合高性能场景下的日志输出。

内容的提问来源于stack exchange,提问作者RevolverOcelot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 14:15:34