|
请使用QQ关联注册PLM之家,学习更多关于内容,更多精彩原创视频供你学习!
您需要 登录 才可以下载或查看,没有账号?注册
x
( N! n+ E( z) o! G" r6 [
两个vector 去重复,相交,合并的函数分享
" t$ l) U" S1 X+ \; J" C
7 F1 ]3 n5 |1 ~8 d0 Y7 o6 T1 v[mw_shl_code=c,true]//容器vector中元素的去重 1 {! P9 T8 W/ ] i' \+ c
vector<int> unique_element_in_vector(vector<int> v){
7 M# _/ a0 r2 g2 V vector<int>::iterator vector_iterator;
: |5 _3 m+ {7 s! [! j! t sort(v.begin(),v.end());
+ h* u( J( q& D, }" E" S, v* P vector_iterator = unique(v.begin(),v.end());
# O+ F' @2 y0 i2 @ E if(vector_iterator != v.end()){
" V2 _3 d& _+ P: c$ w' p v.erase(vector_iterator,v.end()); , f- }6 _; ~4 c
} 2 h: @. _1 w& N
return v; - W8 y0 V1 g: l6 K* g4 i' P
}
G8 w; B0 T9 \6 z- p ( \# l- {5 r. J+ E: d( _" ~1 ?
//两个vector求交集
9 }, i! m" ]+ V7 E. X' xvector<int> vectors_intersection(vector<int> v1,vector<int> v2){ 0 g* c( O1 r9 Y7 V- l
vector<int> v;
; S( S0 K" T, ~, f: N sort(v1.begin(),v1.end());
5 a+ [" x0 C. b/ ?% W sort(v2.begin(),v2.end());
q7 _- m0 T$ p* e. b1 j- Z set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集 # Y4 c6 V" T6 x4 |5 b# `4 x& }
return v;
) N* e" ?! }) Z" I2 d2 g, Y* a}
6 `& w) ]8 t/ V 7 e3 o. W. ~ v c$ I) L
//两个vector求并集 $ d2 g# K) D' b6 J8 m/ \/ D( b
vector<int> vectors_set_union(vector<int> v1,vector<int> v2){
0 ~8 b9 e/ j4 B vector<int> v;
8 ~& E2 ^: d4 p# i sort(v1.begin(),v1.end()); 4 D7 S. ]: f6 i
sort(v2.begin(),v2.end()); - [6 W1 L( q1 ~& |# i! [; F; t
set_union(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集 ) V* g# J! q2 X( l) o8 b1 b, U
return v; & ^2 ]+ Q" y9 j( ] |
} 9 J( L5 ~5 m, o
; E2 ~5 s# _$ u6 Z+ {//判断vector的某一元素是否存在
) z. Z& X- D/ ^* p. O4 J9 g( {bool is_element_in_vector(vector<int> v,int element){
: W6 V$ G) G6 ^; j& L) c I" n vector<int>::iterator it;
$ |5 l7 f! }: f5 j it=find(v.begin(),v.end(),element); 1 T; |# M$ E) D
if (it!=v.end()){ % ? M! G& L# ]! T& a. T5 O
return true;
" T* m" |0 N1 o; m+ t; y } ; K5 A) k: t7 B' s0 U4 L
else{ 0 m5 ~5 q! u. A) h
return false; & ]8 i8 B) J! {
}
6 `/ Y5 X5 o+ b' X) w}
" n% h& ~! w. x) f6 i [/mw_shl_code]
3 G& f$ F: ]7 F! X6 y |
|