码迷,mamicode.com
首页 > 编程语言 > 详细

C/C++一些库函数的实现

时间:2016-07-24 22:32:29      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

1. 编写一个标准strcpy函数

总分值为10,下面给出几个不同得分的答案

以下是2分程序片段

void strcpy(char *dest, char *src)
{
    while ((*dest++ = *src++) != \0);
}

以下是4分程序片段:

//将源字符串加const
void strcpy(char *dest, const char *src)
{
    while ((*dest++ = *src++) != \0);
}

以下是7分程序片段:

//对源地址和目的地址加非NULL断言
void strcpy(char *dest, const char *src)
{
    assert((dest != NULL) && (src != NULL));
    while ((*dest++ = *src++) != \0);
}

以下是10分程序片段:

技术分享
//为了实现链式操作,将目的地址返回
char *strcpy(char *dest, const char *src)
{
    assert((dest != NULL) && (src != NULL));
    if (dest == src) return dest;
    char *addr = dest;
    while ((*dest++ = *src++) != \0);
    return addr;
}
View Code

可以清楚的看到,小小的strcpy竟然暗藏着这么多玄机,真不是盖的!需要多么扎实的基本功才能写一个完美的strcpy啊!

读者看了不同分值的strcpy版本,应该也可以写出一个10分的strlen函数了:

技术分享
int strlen(const char *str)
{
    assert(str != NULL);
    int len = 0;
    while (*str++ != \0) len++;
    return len;
}
View Code

函数strcmp的实现:

技术分享
int strcmp(const char *str1, const char *str2)
{
    assert((str1 != NULL) && (str2 != NULL));
    while (*str1 && *str2 && (*str1 == *str2))
    {
        str1++;
        str2++;
    }
    return *str1 - *str2;
}
View Code

2. 两个int型数据,不用任何的判断语句如 if、switch、?: 等,找出其中的大值

技术分享
int max(int x, int y)
{
    int buf[2] = {x, y};
    unsigned int z = x - y;
    z >>= 31;
    return buf[z];
}
View Code

3. 文件中有一组整数,要求从小到大排序后输出到另一个文件中

技术分享
 1 #include <iostream>
 2 #include <fstream>
 3 #include <vector>
 4 using namespace std;
 5 //simple bubble sort
 6 void sort(vector<int> &data)
 7 {
 8     int temp, n = data.size();
 9     for (int i = 1; i < n; i++)
10         for (int j = 0; j < n-i; j++)
11             if (data[j] > data[j+1])
12             {
13                 temp = data[j];
14                 data[j] = data[j+1];
15                 data[j+1] = temp;
16             }
17 }
18  
19 int main()
20 {
21     ifstream in(".\\data.txt");
22     if (!in)
23     {
24         cout << "open file error!" << endl;
25         exit(1);
26     }
27  
28     int temp;
29     vector<int> data;
30     while (!in.eof())
31     {
32         in >> temp;
33         data.push_back(temp);
34     }
35     in.close();
36  
37     sort(data);
38  
39     ofstream out(".\\result.txt");
40     if (!out)
41     {
42         cout << "create file error!" << endl;
43         exit(1);
44     }
45     for (size_t i = 0; i < data.size(); i++)
46         out << data[i] << " ";
47     out.close();
48 }
View Code

 

C/C++一些库函数的实现

标签:

原文地址:http://www.cnblogs.com/mrsandstorm/p/5701653.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!