文章目录
遍历算法 1. set_intersection()
2. set_union()
3. set_difference()
遍历算法
1. set_intersection()
代码工程
# define _CRT_SECURE_NO_WARNINGS
# include <iostream>
# include <vector>
# include <algorithm>
using namespace std;
class print
{
public:
void operator ( ) ( int val)
{
cout << val << " " ;
}
} ;
void test01 ( )
{
vector< int > v1;
vector< int > v2;
for ( int i = 0 ; i < 10 ; i++ )
{
v1. push_back ( i) ;
v2. push_back ( i + 5 ) ;
}
vector< int > vTarget;
vTarget. resize ( min ( v1. size ( ) , v2. size ( ) ) ) ;
vector< int > :: iterator itEnd = set_intersection ( v1. begin ( ) , v1. end ( ) , v2. begin ( ) , v2. end ( ) , vTarget. begin ( ) ) ;
cout << "交集为:" ;
for_each ( vTarget. begin ( ) , itEnd, print ( ) ) ;
cout << endl;
return ;
}
int main ( )
{
test01 ( ) ;
return 0 ;
}
运行结果
2. set_union()
代码工程
# define _CRT_SECURE_NO_WARNINGS
# include <iostream>
# include <vector>
# include <algorithm>
using namespace std;
class print
{
public:
void operator ( ) ( int val)
{
cout << val << " " ;
}
} ;
void test01 ( )
{
vector< int > v1;
vector< int > v2;
for ( int i = 0 ; i < 10 ; i++ )
{
v1. push_back ( i) ;
v2. push_back ( i + 5 ) ;
}
vector< int > vTarget;
vTarget. resize ( v1. size ( ) + v2. size ( ) ) ;
vector< int > :: iterator itEnd = set_union ( v1. begin ( ) , v1. end ( ) , v2. begin ( ) , v2. end ( ) , vTarget. begin ( ) ) ;
cout << "并集为:" ;
for_each ( vTarget. begin ( ) , itEnd, print ( ) ) ;
cout << endl;
return ;
}
int main ( )
{
test01 ( ) ;
return 0 ;
}
运行结果
3. set_difference()
代码工程
# define _CRT_SECURE_NO_WARNINGS
# include <iostream>
# include <vector>
# include <algorithm>
using namespace std;
class print
{
public:
void operator ( ) ( int val)
{
cout << val << " " ;
}
} ;
void test01 ( )
{
vector< int > v1;
vector< int > v2;
for ( int i = 0 ; i < 10 ; i++ )
{
v1. push_back ( i) ;
v2. push_back ( i + 5 ) ;
}
vector< int > vTarget;
vTarget. resize ( max ( v1. size ( ) , v2. size ( ) ) ) ;
cout << "v1和v2的差集为:" ;
vector< int > :: iterator itEnd = set_difference ( v1. begin ( ) , v1. end ( ) , v2. begin ( ) , v2. end ( ) , vTarget. begin ( ) ) ;
for_each ( vTarget. begin ( ) , itEnd, print ( ) ) ;
cout << endl;
cout << "v2和v1的差集为:" ;
itEnd = set_difference ( v2. begin ( ) , v2. end ( ) , v1. begin ( ) , v1. end ( ) , vTarget. begin ( ) ) ;
for_each ( vTarget. begin ( ) , itEnd, print ( ) ) ;
cout << endl;
return ;
}
int main ( )
{
test01 ( ) ;
return 0 ;
}
运行结果