zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    java分解质因数
    GUID全局唯一标识符
    Oracle-教师信息表(Teacher)
    Oracle-成绩表(Score)
    Oracle-建表course
    Oracle-建表student
    输入输出-复制
    Map
    哈希
    链表
  • 原文地址:https://www.cnblogs.com/Hello-Nolan/p/12305729.html
Copyright © 2011-2022 走看看