c++程序小练习

1、strcpy原型实现

char * my_strcpy(char *des,const char *src) {
    assert((des != nullptr) && (src != nullptr));
        char *address = des;
        while (*src != '\0') {
            *des++ = *src++;
        }
        return address;
}

调用

    char* des=(char*)malloc(sizeof(char)*100) ;
    memset(des,0,sizeof(char)*100);
    my_strcpy(des,"hello world!");
    cout << des<<endl;
    free(des);
    des = nullptr;

 2、宏定义返回两个数中小的一个

#define Min(A,B) ((A)<=(B)?(A):(B))

int main() {
    cout << Min(108,221);
    std::getchar();
    return 0;
}

Min(*p++,q)会导致p自增两次

3、二叉查找

int binary_search(int *a,int num,int val);

int binary_search(int *a, int num, int val) {
    int begin = 0;
    int end = num-1;

    while (begin <= end){
        int mid = begin + ((end - begin) >> 1);//右移一位,表示除以2

        if (a[mid] < val){
            begin = mid + 1;
        }
        else if (a[mid] > val){
            end = mid - 1;
        }
        else
        {
            return mid;
        }
    }
    return -1;
}


int main() {

    int a[] = { 1,5,8,9,50,55,60,61,62,70 };

    cout<< binary_search(a, 16, 60);

    std::getchar();
    return 0;
}

 4、返回字符串不同收字母位置

int str_cmp_diff(const char *str1, const char *str2){

    int i=0;
    while (str1[i] != '\0' && str2[i] != '\0'){
        if ((str1[i] | 0x20) != (str2[i] | 0x20))
            return i + 1;
        i++;
    }
    return 0;
}

int main() {

    cout << str_cmp_diff("hellowrold", "helloxshsa;");
    std::getchar();
    return 0;
}

 

posted @ 2020-05-12 14:01  卖雨伞的小男孩  阅读(253)  评论(0编辑  收藏  举报