您的位置:首页 > 其它

STL_算法_05_集合算法

2016-03-04 13:56 260 查看
◆ 常用的集合算法:

1、

1.1、第6讲 PPT.40

◆ set_union() : 构造一个有序序列,包含两个有序序列的并集。

1.2、第6讲 PPT.40

◆ set_intersection() : 构造一个有序序列,包含两个有序序列的交集。

1.3、第6讲 PPT.40

◆ set_difference() : 构造一个有序序列,该序列保留第一个有序序列中存在而第二个有序序列中不存在的元素。

ZC: VC6 测试代码:

#ifdef WIN32
#pragma warning (disable: 4786)
#endif

#include <string>
#include <vector>
#include <set>

#include <algorithm>    // 算法
#include <numeric>    // 算法
#include <functional>    // 算法

using namespace std;

void main()
{
vector<int> vecIntA;
vecIntA.push_back(1);
vecIntA.push_back(3);
vecIntA.push_back(5);
vecIntA.push_back(7);
vecIntA.push_back(9);

vector<int> vecIntB;
vecIntB.push_back(1);
vecIntB.push_back(3);
vecIntB.push_back(5);
vecIntB.push_back(6);
vecIntB.push_back(8);

vector<int> vecIntC;
vecIntC.resize(10); // ZC: 没有这句,VC6编译的exe执行时会崩溃
//vecIntC.resize(5);    // ZC: 若这里设置的大小 小于7(∵这里结合实际情况,vecIntC的元素最多为7个),则VC6编译的exe在执行过程中:
// ZC:    Debug会报"Debug Error !"==>"DAMAGE: after Normal block (#64) at 0x00332EE8";
// ZC:    Release什么错误都没有,但是由于vecIntC中元素个数较少,放不下的那些数据就被丢弃了。

//并集
set_union(vecIntA.begin(), vecIntA.end(), vecIntB.begin(), vecIntB.end(), vecIntC.begin());    //vecIntC : {1,3,5,6,7,8,9,0,0,0}

int iIdx = 0;
vector<int>::iterator itC = vecIntC.begin();
while (itC != vecIntC.end())
{
printf("[%02d] ==> %d\n", iIdx, *itC);
itC ++;
iIdx ++;
}
printf("\n");

//交集
fill(vecIntC.begin(), vecIntC.end(), 0);
set_intersection(vecIntA.begin(), vecIntA.end(), vecIntB.begin(), vecIntB.end(), vecIntC.begin());    //vecIntC: {1,3,5,0,0,0,0,0,0,0}

iIdx = 0;
itC = vecIntC.begin();
while (itC != vecIntC.end())
{
printf("[%02d] ==> %d\n", iIdx, *itC);
itC ++;
iIdx ++;
}
printf("\n");

//差集
fill(vecIntC.begin(), vecIntC.end(), 0);
set_difference(vecIntA.begin(), vecIntA.end(), vecIntB.begin(), vecIntB.end(), vecIntC.begin());    //vecIntC: {7,9,0,0,0,0,0,0,0,0}

iIdx = 0;
itC = vecIntC.begin();
while (itC != vecIntC.end())
{
printf("[%02d] ==> %d\n", iIdx, *itC);
itC ++;
iIdx ++;
}
}


ZC:控制台输出:

[00] ==> 1
[01] ==> 3
[02] ==> 5
[03] ==> 6
[04] ==> 7
[05] ==> 8
[06] ==> 9
[07] ==> 0
[08] ==> 0
[09] ==> 0

[00] ==> 1
[01] ==> 3
[02] ==> 5
[03] ==> 0
[04] ==> 0
[05] ==> 0
[06] ==> 0
[07] ==> 0
[08] ==> 0
[09] ==> 0

[00] ==> 7
[01] ==> 9
[02] ==> 0
[03] ==> 0
[04] ==> 0
[05] ==> 0
[06] ==> 0
[07] ==> 0
[08] ==> 0
[09] ==> 0
Press any key to continue


?.?、第6讲 PPT.?



ZC: VC6 测试代码:

ZC:控制台输出:

X
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: