|
|
请使用QQ关联注册PLM之家,学习更多关于内容,更多精彩原创视频供你学习!
您需要 登录 才可以下载或查看,没有账号?注册
x
1 Y0 u/ [/ G. o$ X3 I
两个vector 去重复,相交,合并的函数分享
" M& Q2 V1 c: ~$ T5 D8 @
M2 ?0 b- N! s \- ^$ }( S6 Z[mw_shl_code=c,true]//容器vector中元素的去重 3 s% ?& }! x- I! Q. c
vector<int> unique_element_in_vector(vector<int> v){ ) k" p# @- Q: d' v4 J6 @0 x `" f( `
vector<int>::iterator vector_iterator;
: s- n% d; T7 Y9 }! x7 u) j+ @& x; U sort(v.begin(),v.end()); 8 Q2 d. t& \9 v8 J
vector_iterator = unique(v.begin(),v.end());
, D T# c* V: d if(vector_iterator != v.end()){ 7 s z6 ?8 y7 U9 y0 j& u
v.erase(vector_iterator,v.end()); " B. b& I: T) G3 }4 S: V# R8 t
} , ~% H+ A+ I1 N$ y# q# G1 d" D# o
return v; & X- X- ]' N0 x1 T- N0 D6 W
} 3 Z" F! n: |' q: z
" S/ R% g9 r! e6 K//两个vector求交集
8 A1 v8 X$ H( ` i& dvector<int> vectors_intersection(vector<int> v1,vector<int> v2){
2 P( u: E2 x% n) ?. U; A6 B: | vector<int> v;
2 n) A! p& K- d0 M6 C+ A8 i w7 K sort(v1.begin(),v1.end()); 9 M7 T# ?% r: p; T" U( v
sort(v2.begin(),v2.end()); / F5 S# g) A" t0 k7 M
set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集 8 ]6 q3 R. ~8 X1 B0 U/ x1 E9 C
return v;
6 I' h- `6 I- x k0 J6 `}
" w3 h; C5 O, l7 i; V" z1 \/ ]
: u7 y; C' d. m; ?. X; N4 J//两个vector求并集
1 e. t5 A$ }2 S/ tvector<int> vectors_set_union(vector<int> v1,vector<int> v2){ 0 l! E+ _2 m/ x
vector<int> v;
7 ^& M* Z, H1 X: i* S sort(v1.begin(),v1.end());
$ h2 `+ O. z; P; P7 f0 r) q0 b sort(v2.begin(),v2.end()); 9 T0 q& t/ ?; g% V7 C
set_union(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集 ; p4 A% O% u, L8 D0 Y
return v; 9 |7 F) Y: r) U( H% ~! h
} 2 h, K" u- B* F+ D$ F, ], l
, ?% ?) ]9 o- R' ?//判断vector的某一元素是否存在 4 x4 a# a0 G4 a
bool is_element_in_vector(vector<int> v,int element){
* W! r7 k2 X: T- A3 }) e vector<int>::iterator it;
% a: { C1 @2 L& i: Z2 w- ]6 s" z( d it=find(v.begin(),v.end(),element);
$ N/ N+ {6 M+ U7 t if (it!=v.end()){
) L8 s6 E+ i2 B5 v& s$ ` return true;
; H" @* {6 Q, A9 J' \( B1 t- Z; U } - Y1 y5 w0 L2 U7 y! X2 |0 y' H0 w1 G
else{
* w9 O& w& y& f: B return false; ) X, o- }# s9 P+ f
}
9 E5 Q" q5 R2 F# R3 n} . K2 Y( Q$ P+ l9 J% c0 c6 j
[/mw_shl_code]6 y4 Z0 D& C; \* G1 y' ^2 M( E
|
|