|
|
请使用QQ关联注册PLM之家,学习更多关于内容,更多精彩原创视频供你学习!
您需要 登录 才可以下载或查看,没有账号?注册
x
1 \8 o# [+ A2 @& L# M两个vector 去重复,相交,合并的函数分享
* g) K1 R$ U. `3 z/ j4 Q8 a4 [4 f( x: Z
[mw_shl_code=c,true]//容器vector中元素的去重
, Q4 e4 A! w( L ~& D3 i9 ]vector<int> unique_element_in_vector(vector<int> v){ 3 F' T: _9 E1 \6 w
vector<int>::iterator vector_iterator; 6 a) R, [# p. L* `' S, ?; R9 i
sort(v.begin(),v.end()); , f Q2 L, c5 p) g! S9 F! J
vector_iterator = unique(v.begin(),v.end());
& G0 G; q: B+ }5 h$ P5 T0 H if(vector_iterator != v.end()){ 9 N* g! F: E d( V! M1 {3 P" r! k
v.erase(vector_iterator,v.end());
8 a# ^* Q6 r8 S% l- G* w } % X9 i$ a2 _9 s8 u2 e
return v;
# P8 T( `& |6 X1 j+ y9 ^8 Z2 r9 P} 1 s7 h _& m/ ?, I. V6 ]
$ X9 ~$ l9 ]' B9 b4 H3 ^
//两个vector求交集 9 Z0 X2 @% B* S' p6 `7 h( |* }
vector<int> vectors_intersection(vector<int> v1,vector<int> v2){ $ J$ s2 M0 z4 I0 C+ @6 J
vector<int> v;
1 T) _3 }: |4 f; t sort(v1.begin(),v1.end()); $ d+ v7 U" t" J- o i
sort(v2.begin(),v2.end()); $ L4 x0 h' u0 v8 p2 H6 M2 g$ @# r c
set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集
' l0 M) \' J2 r$ J: {. ^ return v;
4 R4 n' G, ~3 B6 Z}
/ U$ C+ `5 N8 G) Z+ h" x7 W
/ } e& g2 n% w8 s; k9 k: e//两个vector求并集
* w3 v U2 G, f, g$ _3 T4 c# j$ X6 Yvector<int> vectors_set_union(vector<int> v1,vector<int> v2){ : O5 N+ C/ L" @+ _* q; ]
vector<int> v; * b$ T- o. d% B
sort(v1.begin(),v1.end()); 1 m2 s5 c0 ~; L9 V. e
sort(v2.begin(),v2.end());
. C8 U; Y3 L' ?9 s5 O set_union(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集
9 A; }/ J2 V8 d' ~: x9 b, a; y return v;
1 v& @, c5 {0 [3 K+ y. K} - D0 s& L( d; w# N* B
# v1 |8 i0 l; H1 H0 Y- I5 b- `
//判断vector的某一元素是否存在 0 [) Y* N) p7 R
bool is_element_in_vector(vector<int> v,int element){
8 u# |1 Z9 v9 r4 W vector<int>::iterator it;
4 q m4 T6 ~5 a6 I' z5 M it=find(v.begin(),v.end(),element); : F8 n7 o$ i$ O y9 s
if (it!=v.end()){
% ~# S% d5 j. H1 V1 K5 p return true; , e& V. u( [; z& g& y
}
! y( J9 V9 |4 J. c2 B2 Z" @' ~! m else{
' T3 D \9 U- A L3 L. [' h7 I return false;
' b$ O" d% m. N( j6 G }
7 C3 [* D4 r9 v4 J# K W} ! e V9 S5 L3 b% B; c2 O
[/mw_shl_code]$ F7 o) N: p; v& e* H" }
|
|