12. 判定不等最小索引函数

题目:

编写一个模板函数 mismatch,返回值是使不等式 a[i] ≠ b[i]成立的最小索引 i ,0 ≤ i < n 。

思路:

传入两个数组(假定两数组元素个数相同,否则没有意义),依次比较元素即可。有不匹配时返回下标,完全匹配时返回 -1。

代码:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 template <typename T>
 5 int my_mismatch (const T* a, const T* b, int size) {
 6     int i = 0;
 7     while (i < size) {
 8         if (a[i] != b[i]) {
 9             return i;
10         }
11         ++i;
12     }
13     return -1;
14 }
15 
16 int main() {
17     int a[5] { 0, 1, 2, 3, 4 };
18     int a_copy[5] { 0, 1, 2, 3, 4 };
19     int b[5] { 0, 1, 3, 3, 4 };
20     int index = my_mismatch(a, b, 5);
21     cout << "Mismatch index : " << index << endl;
22     index = my_mismatch(a, a_copy, 5);
23     cout << "Mismatch index : " << index << endl;
24 
25     return 0;
26 }

猜你喜欢

转载自www.cnblogs.com/Hello-Nolan/p/12305729.html