|
|
请使用QQ关联注册PLM之家,学习更多关于内容,更多精彩原创视频供你学习!
您需要 登录 才可以下载或查看,没有账号?注册
x
' n `) c5 t S* w
两个vector 去重复,相交,合并的函数分享
0 W/ z; u$ R2 j' Q# ~. o
% {- P$ ^1 b( h4 C6 f- G9 d2 x$ x# v[mw_shl_code=c,true]//容器vector中元素的去重
# c) n0 R; j- h/ z3 lvector<int> unique_element_in_vector(vector<int> v){ 5 ]2 s, U. U- ~# \* r K
vector<int>::iterator vector_iterator;
3 h% I- u& q6 S% d sort(v.begin(),v.end());
E% Y. H8 U2 O% K0 ?+ T2 d6 O; o vector_iterator = unique(v.begin(),v.end()); % T1 r% a3 F# K) W$ u& @* K- |
if(vector_iterator != v.end()){ % e- l, i1 @0 Y9 g! d% E! Y
v.erase(vector_iterator,v.end());
, Y- H; Q- Q* A9 V: C1 V7 U5 H6 x3 V }
4 {, X) @5 q4 Z( }4 ^6 h return v;
' x7 Y6 N8 ~0 |. X) W} 6 I" V+ b+ G/ v' x1 ]$ |
' y; J- v7 t' q//两个vector求交集 " p# B8 ^9 K) x- F
vector<int> vectors_intersection(vector<int> v1,vector<int> v2){
. O. t( v$ }* a) R% s, D6 d$ |; ^7 n vector<int> v; l% _& U/ @" h8 w& z
sort(v1.begin(),v1.end());
4 o+ k; f' n3 G$ Q sort(v2.begin(),v2.end()); - T5 }. b' n7 u
set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集
2 A3 k; O- q, G! ^ return v;
2 D: A: {1 C5 J( z R} - D& e Q' Y4 `# |$ L0 |" g
9 q; Z' I/ U; V; r4 @//两个vector求并集 0 X6 d: t) `/ A) ]3 U
vector<int> vectors_set_union(vector<int> v1,vector<int> v2){
' W9 o- P% u. @ vector<int> v; " |( h: W7 S X3 f
sort(v1.begin(),v1.end());
2 n- W" K2 ^7 k) x, {8 ^" ` sort(v2.begin(),v2.end()); 4 f- [. }, E9 Q! o; P
set_union(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集
" R! u* g' ^' K return v;
* n4 c- k6 g$ d2 l3 M) h h! G1 Z} $ w, ^! o. b! K) C& I5 a
- w/ c) A9 ^: b2 Z
//判断vector的某一元素是否存在 + P; Z, z* u2 D0 c! _- Z
bool is_element_in_vector(vector<int> v,int element){
0 t/ z% ? B) K. \5 c* l1 M1 Z vector<int>::iterator it; 3 h: W+ V6 ?$ |
it=find(v.begin(),v.end(),element);
1 Y# d3 B8 k% ]( c8 E: h) y if (it!=v.end()){
9 \: k: n4 v9 [5 c4 z& c return true; : X% P( h1 Z# F8 r" Q: J1 c* ~
} $ A. J* z; e) v& q- `/ S3 v( i
else{
% W2 `( _! z \5 R+ z8 [9 t return false;
( |- r+ `1 s: {# w9 \' U }
+ @' @3 i) G/ Y! C i6 e}
{: N3 [+ B, l [/mw_shl_code]
, g4 E$ h' K! y* v |
|