C++ 函数

函数和C type 字符串

简单统计

#include <iostream>
#include <array>
#include <vector>
using namespace std;
unsigned int c_in_str(const char *str, char ch);
int main()
{
    char mmm[15] = "minimum";
    char * wail = "ululate";
    unsigned int ms = c_in_str(mmm, 'm');
    unsigned int us = c_in_str(wail, 'u');
    cout << "ucount:" << us << endl;
    cout << "count:" << ms << endl;

    return 0;
}

unsigned int c_in_str(const char *str, char ch)
{
    unsigned int count = 0;
    while (*str)
    {
        if (*str == ch)
        {

            count++;
        }
        str++;
    }
    return count;
}

输入个数和展示

#include <iostream>
#include <array>
#include <vector>
using namespace std;
unsigned int c_in_str(const char *str, char ch);
char *buildStr(char ch, int n);
int main()
{
    int times;
    char ch;
    cout << "Enter a character:";
    cin >> ch;
    cout << "Enter an integer: ";
    cin >> times;
    char *ps = buildStr(ch, times);
    cout << ps << endl;
    delete [] ps;
    cout << ps << endl;
    ps = buildStr('+', 9);
    cout << ps << endl;
    delete [] ps;
    return 0;
}

char *buildStr(char ch, int n)
{
    char *pstr = new char[n + 1];
    *(pstr + n) = '\0';
    while (n-- > 0)
    {
        pstr[n] = ch;
    }
    return pstr;
}

unsigned int c_in_str(const char *str, char ch)
{
    unsigned int count = 0;
    while (*str)
    {
        if (*str == ch)
        {

            count++;
        }
        str++;
    }
    return count;
}

函数和string

#include <iostream>
using namespace std;
const int SIZE = 5;
void display(const string * ar,int n);
int main()
{
    string list[SIZE];
    cout << "Enter your " << SIZE << " string. " << endl;
    for (int i = 0; i < SIZE; i++)
    {
        cout << i + 1 << ": ";
        getline(cin, list[i]);
    }

    cout << "your list:\n";
    display(list,SIZE);

    return 0;
}

void display(const string * ar,int n) 
{
    for (int i = 0; i < n; i++)
    {
        cout << i + 1 << ": " + *(ar + i) <<endl;
    }
    
}

函数和结构体

坐标转换,传地址

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;


const int Mins_per_hr = 60;



struct polar
{
    double distance;
    double angle;
};

struct rect
{
    double x;
    double y;
};


void showPolar(const polar* p);
void rect_to_polar(const rect * xypos,polar * pda);
int main()
{
    rect rplace;
    polar pplace;
    cout << "Enter the x and y values: ";
    while (cin >> rplace.x >> rplace.y)
    {
        rect_to_polar(&rplace,&pplace);
        showPolar(&pplace);
    }
}

void showPolar(const polar * p)
{
    const double Rad_to_deg = 57.29577951;
    cout << "polar distance:" << p->distance << ",polar angle:" << p->angle*Rad_to_deg << endl;
}

void rect_to_polar(const rect * xypos,polar * pda)
{
    pda->distance = sqrt(xypos->x) + sqrt(xypos->y);
    pda->angle = atan2(xypos->y, xypos->x);
}

坐标转换,传值。时间结构计算时间

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
struct travel_time
{
    int hours;
    int mins;
};

travel_time sum(travel_time t1, travel_time t2);
void show_time(travel_time time);
const int Mins_per_hr = 60;



struct polar
{
    double distance;
    double angle;
};

struct rect
{
    double x;
    double y;
};


void showPolar(polar p);
polar rect_to_polar(rect xypos);

int main()
{
    rect rplace;
    polar pplace;
    cout << "Enter the x and y values: ";
    while (cin >> rplace.x >> rplace.y)
    {
        pplace = rect_to_polar(rplace);
        showPolar(pplace);
    }
}

void showPolar(polar p)
{
    const double Rad_to_deg = 57.29577951;
    cout << "polar distance:" << p.distance << ",polar angle:" << p.angle*Rad_to_deg << endl;
}

polar rect_to_polar(rect xypos)
{
    polar answer;
    answer.distance = sqrt(xypos.x) + sqrt(xypos.y);
    answer.angle = atan2(xypos.y, xypos.x);
    return answer;
}

int main2()
{

    travel_time day1 = {5, 45};
    travel_time day2 = {4, 55};
    travel_time trip = sum(day1, day2);

    cout << "2 day total:";

    show_time(trip);
    travel_time day3 = {4, 32};
    show_time(sum(trip, day3));

    return 0;
}

void show_time(travel_time time)
{
    cout << "hours:" << time.hours << ",mins " << time.mins << endl;
}

travel_time sum(travel_time t1, travel_time t2)
{
    travel_time total;

    total.mins = (t1.mins + t2.mins) % 60;
    total.hours = t1.hours + t2.hours + (t1.mins + t2.mins) / 60;

    return total;
}

函数和数组

记录四季消费和总额

#include <iostream>
#include <string>
using namespace std;
const int Seasons = 4;
const array<string, Seasons> Snames = {"Spring", "Summer", "Fall", "Winter"};
void fill(array<double, Seasons> *pa);
void show(array<double, Seasons> ds);
int main()
{
    array<double, Seasons> expenses;
    fill(&expenses);
    show(expenses);
    return 0;
}

void show(array<double, Seasons> ds)
{
    double total = 0.0;
    cout << "\nExpenses\n";
    for (int i = 0; i < Seasons; i++)
    {
        cout << Snames[i] << ": $" << ds[i] << endl;
        total += ds[i];
    }
    cout << "total: $" << total << endl;
}

void fill(array<double, Seasons> *pa)
{
    for (int i = 0; i < Seasons; i++)
    {
        cout << "Enter " << Snames[i] << " expenses: ";
        cin >> (*pa)[i];
    }
}

函数的递归

基本递归

#include <iostream>
#include <string>
using namespace std;
void countdown(int n);
int main()
{
    countdown(4);
    return 0;
}

void countdown(int n)
{
    cout << "Countdown......" <<  n << " " << &n << endl;
    if(n > 0) 
    {
        countdown(n - 1);
    }
    cout << n << " kaboom!" << " " << &n << endl;
}

复杂输出递归函数

#include <iostream>
#include <string>
using namespace std;
const int Len = 66;
const int Divs = 6;
void subdivide(char *ar, int low, int high, int level);
int main()
{
    char ruler[Len];
    for (int i = 1; i < Len - 2; i++)
    {
        ruler[i] = ' ';
    }
    ruler[Len - 1] = '\0';

    int max = Len - 2;
    int min = 0;

    ruler[0] = ruler[max] = '|';
    cout << ruler << endl;

    for (int i = 1; i <= Divs; i++)
    {
        subdivide(ruler, min, max, i);
        cout << ruler << endl;
        for (int j = 0; j < Len - 2; j++)
        {
            ruler[i] = ' ';
        }
    }

    return 0;
}

void subdivide(char *ar, int low, int high, int level)
{
    if (level == 0)
        return;

    int mid = (low + high) / 2;
    ar[mid] = '|';
    subdivide(ar, low, mid, level - 1);
    subdivide(ar, mid, high, level - 1);
}

|                                                               |
|                               |                               |
|               |               |               |               |
|       |       |       |       |       |       |       |       |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

函数指针

获取函数地址
声明函数指针
使用函数指针调用函数

#include <iostream>
#include <string>
using namespace std;
double betsy(int lns);
double pam(int lns);
void estimate(int lines, double (*pf)(int));

int main()
{
    int code;
    cout << "How many lines of code do you need? ";
    cin >> code;
    cout << "Here's Betsy's estimate:\n";
    estimate(code, betsy);
     cout << "Here's Pam's estimate:\n";
    estimate(code, pam);
    return 0;
}

void estimate(int lines, double (*pf)(int))
{
    cout << lines << "lines wiil take " << (*pf)(lines) << endl;
}

double betsy(int lns)
{
    return 0.05 * lns;
}

double pam(int lns)
{
    return 0.03 * lns + 0.0004 * lns * lns;
}

默认参数

#include <iostream>
#include <string>
using namespace std;
const int ArSize = 80;
char *left(const char *str, int n = 1);
int main()
{
    char sample[ArSize];
    cout << "Enter a string: \n";
    cin.get(sample, ArSize);
    char *ps = left(sample, 4);
    cout << ps << endl;
    ps = left(sample);
    cout << ps << endl;
    delete[] ps;
    return 0;
}

char *left(const char *str, int n)
{
    if (n < 0)
        n = 0;
    char *p = new char[n + 1];
    int i;
    for (i = 0; i < n && str[i]; i++)
    {
        p[i] = str[i];
    }
    while (i <= n)
    {
        p[i++] = '\0';
    }
    return p;
}

优化1

char *left(const char *str, int n)
{    
    int len = strlen(str);
    if (n < 0)
        len = 0;
    char *p = new char[len + 1];
    int i;
    for (i = 0; i < n && str[i]; i++)
    {
        p[i] = str[i];
    }
    while (i <= len)
    {
        p[i++] = '\0';
    }
    return p;
}

优化2

char *left(const char *str, int n)
{
    int m = 0;
    while (m <= n && str[m])
        m++;
    char *p = new char[m + 1];
    int i;
    for (i = 0; i < n && str[i]; i++)
    {
        p[i] = str[i];
    }
    while (i <= m)
    {
        p[i++] = '\0';
    }
    return p;
}

函数重载记录数字个数

#include <iostream>
#include <string>
using namespace std;
char *left(const char *str, int n = 1);
unsigned long left(unsigned long num, unsigned ct);

int main()
{
    unsigned long n = 12345678;
    const char * trip = "Hawaii!!";
    char * temp;
    int i;
    for (i = 0; i < 10; i++)
    {
        cout << left(n, i) << endl;
        temp = left(trip, i);
        cout << temp << endl;
        delete[] temp;
    }

    return 0;
}



char *left(const char *str, int n)
{
    int m = 0;
    while (m <= n && str[m])
        m++;
    char *p = new char[m + 1];
    int i;
    for (i = 0; i < n && str[i]; i++)
    {
        p[i] = str[i];
    }
    while (i <= m)
    {
        p[i++] = '\0';
    }
    return p;
}

unsigned long left(unsigned long num, unsigned ct)
{
    unsigned digits = 1;
    unsigned long n = num;
    if (ct == 0 || num == 0)
        return 0;

    while (n /= 10)
        digits++;

    if (digits > ct)
    {
        ct = digits - ct;

        while (ct--)
            num /= 10;
        return num;
    }
    else
        return num;
}

引用重载

void staff(double &rs);
void staff(const double &rcs);
void stove(double &r1);
void stove(const double &r2);
void stove(double &&r3);

模板函数

template <typename T>
void Swap(T &a,T &b)
{
    T temp;
    temp =a;
    a = b;
    b = temp;
}

模版函数重载

include <iostream>
#include <string>
using namespace std;
const int Limit = 8;


void swapr(int & a, int & b);
void swapr2(int * a, int * b);
void swapr3(int a, int  b);
template <typename T>
void Swap(T &a,T &b)
{
    T temp;
    temp =a;
    a = b;
    b = temp;
}

template <typename T>
void Swap(T *a,T *b,int n)
{
    T temp;
    for (int i = 0; i < n; i++)
    {
        temp = a[i];
        a[i] = b[i];
        b[i] = temp;
    }
    
}


void show(int a[]);

int main()
{
    int wallet1 = 100;
    int wallet2 = 350;
    cout << "wallet1 = "<< wallet1 << " wallet2 = " << wallet2 << endl;
    cout << "using references to swap contents:\n";
    swapr(wallet1,wallet2);
    cout << "wallet1 = "<< wallet1 << " wallet2 = " << wallet2 << endl;

    cout << "using pointers to swap contents:\n";
    swapr2(&wallet1,&wallet2);
    cout << "wallet1 = "<< wallet1 << " wallet2 = " << wallet2 << endl;
    cout << "using value to swap contents:\n";
    swapr3(wallet1,wallet2);
    cout << "wallet1 = "<< wallet1 << " wallet2 = " << wallet2 << endl;

    
    Swap(wallet1,wallet2);
    cout << "wallet1 = "<< wallet1 << " wallet2 = " << wallet2 << endl;

    double i = 20;
    double j = 30;
    Swap(i,j);
        cout << "i = "<< i << " j = " << j << endl;

    int d1[Limit] = {2,3,4,5,1,7,8,9};
    int d2[Limit] = {2,3,2,6,1,8,9,9};
    show(d1);
    show(d2);
    Swap(d1,d2,Limit);
    show(d1);
    show(d2);

    return 0;
}

void swapr(int & a, int & b)
{
    int temp = a;
    a = b;
    b = temp;
}
void swapr2(int * a, int * b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void swapr3(int a, int  b)
{
    int temp = a;
    a = b;
    b = temp;
}


void show(int * a)
{
    cout << a[0] << a[1] << "/";
     cout << a[2] << a[3] << "/";
     for (int i = 4; i < Limit; i++)
     {
        cout << a[i];
     }

     cout << endl;
     

}
  1. 非模版函数
    void Swap(job &, job &);
  2. 模版函数
    template <typename T>
    void Swap(T &, T &);
  3. 根据模版生成的具体化函数
    template <> void Swap<job>(job &, job &);

如果出现冲突,编译器识别优先级,非模版函数 》 模版生成的具体函数

隐式实例化:编译器帮我们生成的代码。
显示具体化:程序员,根据某个模版要求编译器生成具体的函数
template <> void Swap<job>(job &, job &)
{......}
另外一种模版显示实例化:template void Swap<int>(int, int);

#include <iostream>
#include <string>
using namespace std;

struct debts
{
    char name[50];
    double amount;
};

template <typename T>
void ShowArray(T arr[], int n);

template <typename T>
void ShowArray(T ** arr,int n);

int main()
{
    int things[6] = {13, 31, 103, 301, 310, 130};
    struct debts mr_E[3] =
        {
            {"Ima Wolfe", 2400.0},
            {"Ura Foxe", 1300.0},
            {"David", 1800.0}};
    double *pd[3];
    for (int i = 0; i < 3; i++)
    {
        pd[i] = &mr_E[i].amount;
    }

    "cout << Liting Mr.E's debts:\n";
    ShowArray(things,6);
    ShowArray(pd, 3);

    return 0;
}

template <typename T>
void ShowArray(T * arr, int n)
{
    cout << "templateA\n";
    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << ' ';
        cout << endl;
    }
}
template <typename T>
void ShowArray(T ** arr,int n)
{
    cout << "templateB\n";
    for (int i = 0; i < n; i++)
    {
        cout << *arr[i] << ' ';
        cout << endl;
    }

}

根据模版生成的具体化函数 编译的时候会动态找合适的模版,如果void ShowArray(T ** arr,int n) 去掉的话,那么, ShowArray(pd, 3); 打印的将会是地址。加上这个模版打印的就是具体的数值了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,126评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,254评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,445评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,185评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,178评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,970评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,276评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,927评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,400评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,883评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,997评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,646评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,213评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,204评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,423评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,423评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,722评论 2 345

推荐阅读更多精彩内容