(原創) 如何找出兩個container中相同元素的個數? (C/C++) (STL)
這原是我C++ Lab的一題,不過我簡化了題目,改用兩個簡單的vector去比較,找出相同元素的個數。
1/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : GenericAlgo_find_first_of2.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use find_first_of() to find same element in both container
7Release : 12/14/2006 1.0
8*/
9#include <iostream>
10#include <vector>
11#include <algorithm>
12
13using namespace std;
14
15int main() {
16 int ia1[] = {1,2,3,4,5};
17 int ia2[] = {7,4,4,5,3};
18
19 vector<int> ivec1(ia1, ia1 + sizeof(ia1) / sizeof(int));
20 vector<int> ivec2(ia2, ia2 + sizeof(ia2) / sizeof(int));
21
22 vector<int>::iterator iter1_begin = ivec1.begin();
23
24 int count = 0;
25 while(iter1_begin != ivec1.end()) {
26 vector<int>::iterator iter = find_first_of(iter1_begin, ivec1.end(), ivec2.begin(), ivec2.end());
27 if (iter != ivec1.end()) {
28 ++count;
29 iter1_begin = ++iter;
30 }
31 else {
32 break;
33 }
34 }
35
36 cout << count << endl;
37
38 return 0;
39}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : GenericAlgo_find_first_of2.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use find_first_of() to find same element in both container
7Release : 12/14/2006 1.0
8*/
9#include <iostream>
10#include <vector>
11#include <algorithm>
12
13using namespace std;
14
15int main() {
16 int ia1[] = {1,2,3,4,5};
17 int ia2[] = {7,4,4,5,3};
18
19 vector<int> ivec1(ia1, ia1 + sizeof(ia1) / sizeof(int));
20 vector<int> ivec2(ia2, ia2 + sizeof(ia2) / sizeof(int));
21
22 vector<int>::iterator iter1_begin = ivec1.begin();
23
24 int count = 0;
25 while(iter1_begin != ivec1.end()) {
26 vector<int>::iterator iter = find_first_of(iter1_begin, ivec1.end(), ivec2.begin(), ivec2.end());
27 if (iter != ivec1.end()) {
28 ++count;
29 iter1_begin = ++iter;
30 }
31 else {
32 break;
33 }
34 }
35
36 cout << count << endl;
37
38 return 0;
39}
執行結果
3
請按任意鍵繼續 . . .
請按任意鍵繼續 . . .
其中較爭議的是,ivec2有重複,需先unique嗎?我第一個版本就有去unique(),但事實上find_first_of()並不需要是先unique()過,結果仍會一樣,至於速度會不會有差,我目前還無定論,這點我再請教老師看看。