(原創) 如何找出兩個container中相同元素的個數? (C/C++) (STL)

這原是我C++ Lab的一題,不過我簡化了題目,改用兩個簡單的vector去比較,找出相同元素的個數。

 1 ExpandedBlockStart.gif ContractedBlock.gif /**/ /* 
 2InBlock.gif(C) OOMusou 2006 http://oomusou.cnblogs.com
 3InBlock.gif
 4InBlock.gifFilename    : GenericAlgo_find_first_of2.cpp
 5InBlock.gifCompiler    : Visual C++ 8.0 / ISO C++
 6InBlock.gifDescription : Demo how to use find_first_of() to find same element in both container
 7InBlock.gifRelease     : 12/14/2006 1.0
 8ExpandedBlockEnd.gif*/

 9 None.gif#include  < iostream >
10 None.gif#include  < vector >
11 None.gif#include  < algorithm >
12 None.gif
13 None.gif using   namespace  std;
14 None.gif
15 ExpandedBlockStart.gifContractedBlock.gif int  main()  dot.gif {
16ExpandedSubBlockStart.gifContractedSubBlock.gif  int ia1[] = dot.gif{1,2,3,4,5};
17ExpandedSubBlockStart.gifContractedSubBlock.gif  int ia2[] = dot.gif{7,4,4,5,3};
18InBlock.gif
19InBlock.gif  vector<int> ivec1(ia1, ia1 + sizeof(ia1) / sizeof(int));
20InBlock.gif  vector<int> ivec2(ia2, ia2 + sizeof(ia2) / sizeof(int));
21InBlock.gif
22InBlock.gif  vector<int>::iterator iter1_begin = ivec1.begin();
23InBlock.gif
24InBlock.gif  int count = 0;
25ExpandedSubBlockStart.gifContractedSubBlock.gif  while(iter1_begin != ivec1.end()) dot.gif{
26InBlock.gif    vector<int>::iterator iter = find_first_of(iter1_begin, ivec1.end(), ivec2.begin(), ivec2.end());
27ExpandedSubBlockStart.gifContractedSubBlock.gif    if (iter != ivec1.end()) dot.gif{
28InBlock.gif      ++count;
29InBlock.gif      iter1_begin = ++iter;
30ExpandedSubBlockEnd.gif    }

31ExpandedSubBlockStart.gifContractedSubBlock.gif    else dot.gif{
32InBlock.gif      break;
33ExpandedSubBlockEnd.gif    }

34ExpandedSubBlockEnd.gif  }

35InBlock.gif
36InBlock.gif  cout << count << endl;
37InBlock.gif
38InBlock.gif  return 0;
39ExpandedBlockEnd.gif}


執行結果

None.gif 3
None.gif請按任意鍵繼續 . . .


其中較爭議的是,ivec2有重複,需先unique嗎?我第一個版本就有去unique(),但事實上find_first_of()並不需要是先unique()過,結果仍會一樣,至於速度會不會有差,我目前還無定論,這點我再請教老師看看。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值