c++ STL set_difference set_intersection set_union 操作

2025-05-27 0 82

以下是STL algorithm的几个函数,使用的条件是有序容器,所以 vector在被sort了之后是可以使用的,set也是可以使用的。

set_difference 这个是求得在第一个容器中有,第二个容器中没有的。set_intersection 求两个容器的交, set_union 求两个容器的并。

set_symmetric_difference 求两个容器的差。

最后使用的时候注意要提前分配好最后的盛放容器,其大小最好是两个操作容器的和,然后需要根据返回的迭代器resize一下,看下面的例子。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25
// set_symmetric_difference example

#include <iostream> // std::cout

#include <algorithm> // std::set_symmetric_difference, std::sort

#include <vector> // std::vector

int main () {

int first[] = {5,10,15,20,25};

int second[] = {50,40,30,20,10};

std::vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0

std::vector<int>::iterator it;

std::sort (first,first+5); // 5 10 15 20 25

std::sort (second,second+5); // 10 20 30 40 50

it=std::set_symmetric_difference (first, first+5, second, second+5, v.begin());

// 5 15 25 30 40 50 0 0 0 0

v.resize(it-v.begin()); // 5 15 25 30 40 50

std::cout << "The symmetric difference has " << (v.size()) << " elements:\\n";

for (it=v.begin(); it!=v.end(); ++it)

std::cout << ' ' << *it;

std::cout << '\\n';

return 0;

}

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 c++ STL set_difference set_intersection set_union 操作 https://www.kuaiidc.com/74209.html

相关文章

发表评论
暂无评论