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

如何在不使用容器的情况下使用输出迭代器实现无存储的集合交集操作?

如何在不使用容器的情况下使用输出迭代器实现无存储的集合交集操作?

嘿,咱们来聊聊这个问题。通常用std::set_intersection计算两个有序容器的交集时,大家可能会习惯把结果存到另一个容器里,但其实完全可以跳过这一步,直接用输出迭代器把结果输出出去,不用额外存储。

先看个完整的实现示例,咱们基于常见的集合交集代码修改成无存储版本:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main() {
    std::vector<int> v1{7, 2, 3, 4, 5, 6, 7, 8};
    std::vector<int> v2{5, 7, 9, 7};
    
    // 注意:std::set_intersection要求输入容器是有序的,所以先排序
    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());
    
    // 直接用ostream_iterator作为输出迭代器,把结果打印到控制台
    std::cout << "交集元素:";
    std::set_intersection(
        v1.begin(), v1.end(),
        v2.begin(), v2.end(),
        std::ostream_iterator<int>(std::cout, " ")
    );
    std::cout << std::endl;
    
    return 0;
}

运行这段代码,你会直接在控制台看到输出的交集元素:5 7 7 ,全程没用到额外的容器来存储结果。

原理其实很直白:std::ostream_iterator本身就是个输出迭代器,它重载了operator=,当std::set_intersection往这个迭代器赋值时,就会自动把对应的值输出到绑定的流(这里是标准输出)里,完美实现无存储的交集输出。

要是你想把结果输出到文件也很简单,把std::cout换成std::ofstream对象就行:

#include <fstream>
// ...其他头文件不变
int main() {
    // ...排序步骤不变
    std::ofstream outfile("intersection_result.txt");
    std::set_intersection(
        v1.begin(), v1.end(),
        v2.begin(), v2.end(),
        std::ostream_iterator<int>(outfile, "\n")
    );
    outfile.close();
    return 0;
}

这样就能直接把交集元素逐行写入文件,同样不需要中间容器过渡。

备注:内容来源于stack exchange,提问作者Michaël

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 16:58:12