第6章 函数
Posted COCO_PEAK_NOODLE
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第6章 函数相关的知识,希望对你有一定的参考价值。
1-交换2个变量
void swap(int* lhs, int* rhs)
{
int tmp;
tmp = *lhs;
*lhs = *rhs;
*rhs = tmp;
}
2-&的存在是为了去指针?,然后和拷贝区别开?
void reset(int &i)
{
i = 0;
}
int main()
{
int i = 42;
reset(i);
std::cout << i << std::endl;
return 0;
}
3-使用引用交换数据
void swap(int& lhs, int& rhs)
{
int temp = lhs;
lhs = rhs;
rhs = temp;
}
4-指针是固定值,指针指向的值是固定值
#include <iostream>
using std::cout;
int larger_one(const int i, const int *const p)
{
return (i > *p) ? i : *p;
}
int main()
{
int i = 6;
cout << larger_one(7, &i);
return 0;
}
5-交换地址,&是变量的别名,指针也是一个变量
//int*& 实际传入的是指针,&意思是别名
void swap(int*& lft, int*& rht)
{
auto tmp = lft;
lft = rht;
rht = tmp;
}
int main()
{
int i = 42, j = 99;
auto lft = &i;
auto rht = &j;
std::cout << "lft " << lft << std::endl;
std::cout << "rht " << rht << std::endl;
swap(lft, rht);
std::cout << *lft << " " << *rht << std::endl;
std::cout << "lft " << lft << std::endl;
std::cout << "rht " << rht << std::endl;
return 0;
}
输出
lft 0x7ffc3bdddca0
rht 0x7ffc3bdddca4
99 42
lft 0x7ffc3bdddca4
rht 0x7ffc3bdddca0
6-传递数组,感觉现在用vector的多一些吧
#include <iostream>
using std::cout; using std::endl; using std::begin; using std::end;
void print(const int *pi)
{
if(pi)
cout << *pi << endl;
}
void print(const char *p)
{
if (p)
while (*p) cout << *p++;
cout << endl;
}
void print(const int *beg, const int *end)
{
while (beg != end)
cout << *beg++ << endl;
}
void print(const int ia[], size_t size)
{
for (size_t i = 0; i != size; ++i) {
cout << ia[i] << endl;
}
}
void print(int (&arr)[2])
{
for (auto i : arr)
cout << i << endl;
}
int main()
{
int i = 0, j[2] = { 0, 1 };
char ch[5] = "pezy";
print(ch);
print(begin(j), end(j));
print(&i);
print(j, end(j)-begin(j));
print(j);
return 0;
}
7- int强转string
在这里插入代码片
8-如何定义函数指针类型,及使用
#include <iostream>
#include <string>
#include <vector>
using std::vector; using std::cout;
//
// @brief Exercise 6.54
// @note define the function type fp
//
inline int f(const int, const int);
typedef decltype(f) fp;//fp is just a function type not a function pointer
//
// @brief Exercise 6.55
// @note Store pointers to these functions in the vector
//
inline int NumAdd(const int n1, const int n2) { return n1 + n2; }
inline int NumSub(const int n1, const int n2) { return n1 - n2; }
inline int NumMul(const int n1, const int n2) { return n1 * n2; }
inline int NumDiv(const int n1, const int n2) { return n1 / n2; }
vector<fp*> v{ NumAdd, NumSub, NumMul, NumDiv };
int main()
{
//
// @brief Exercise 6.56
// @note Call each element in the vector and print their result.
//
for (auto it = v.cbegin(); it != v.cend(); ++it)
cout << (*it)(2, 2) << std::endl;
return 0;
}
9-最简单的递归
int fact(int val)
{
if (val == 0 || val == 1) return 1;
else return val * fact(val-1);
}
以上是关于第6章 函数的主要内容,如果未能解决你的问题,请参考以下文章