essential c++
=========================第二章复习======================
- 按引用传递和按指针传递容器的值的区别
需要注意,当传递引用的时候,可直接在parameter中写vector的名字(如vec),但当传递指针的时候需要对容器取地址,故需要在vec前加取址符&。
- 声明inline函数(内联函数)
此操作主要应用于对程序的运行速度的优化,当为了将一个函数拆成多个函数从而提高某一部分的利用率时,又不想损失函数调用浪费的时间和内存便可以将这些函数声明为inline function,在每个函数调用点上会将整个inline函数展开,从而使其成为一个函数的副本,减少了函数调用所产生的负担。
- 定义并使用模板函数
为了让一个函数可以很好的兼容各种数据类型,c++提供了模板函数,我们通过function template将函数中不同的地方抽离出来,这样就可以定义一份不需要其他修改的函数模板。这里提供将数据类型抽离出来的情形。
#include<iostream>
#include<vector>
using namespace std;
template <typename elemtype>
void display(const vector<elemtype> &vec)
{
for(int i=0;i<vec.size();i++)
{
cout<<vec[i]<<' ';
}
return;
}
int main(void)
{
int a[7]={1,2,3,4,5,6,7};
char m[7]="\nacdef";
vector<int> vec1(a,a+7);
vector<char> vec2(m,m+7);
display(vec1);
display(vec2);
return 0;
}
- 函数指针
之前一直不知道这东西有啥用,直接调用就是咯,但后来发现这东西也是为了优化程序性能的感觉。。。首先,函数指针的声明
type (*func)(type,type)
这里是声明了一个func的函数指针,返回类型为type并且含有两个类型为type的parameter.同时需要注意,函数指针只在需要调用该函数的时候声明,还有在使用该函数指针的时候,需要单独声明,并将函数名赋值给该指针。
#include<iostream>
#include<vector>
using namespace std;
double a,b;
double set()
{
cout<<"set the length and width"<<'\n';
cin>>a>>b;
return 0.0;
}
double triangle(double a,double b)
{
return a*b*0.5;
}
double rectangle(double a,double b)
{
return a*b;
}
double get_ans(double(*p)(double a,double b),double a,double b)
{
double ans=p(a,b);
cout<<ans<<endl;
}
int main(void)
{
set();
bool choice;
double(*p)(double a,double b);
cout<<"if you want to caculate a rectangle write down 1"
<<"\nif you want a triangle write down 0"<<endl;
cin>>choice;
if(choice)
{
p=rectangle;
get_ans(p,a,b);
}
else
{
p=triangle;
get_ans(p,a,b);
}
return 0;
}