1.计算程序执行时间:
#include<time.h>
clock_t start,end;
start=clock();
//doing code
end=clock();
cout<<end-start<<endl;
2.求0到99的随机整数(包含0和99)
//rand()函数随机产生一个0到MAX的整数。所以要满足上面功能只需要:
#include<time.h>
srand((int)time(NULL));
int a=rand()%100;//a为0-99的随机数
//要求a-b之间的随机数的话;
int a=rand()%(b-a+1)+a;
3.用代码添加库文件。
#pragma comment(lib,"glew32.lib")
4.使用qsort进行快速排序
//qsort可以对集合数组进行快速排序,集合数组包括一维数组,二维数组。。结构体数组。。。
//void qsort(void *base,int nelem,int width,int (*fcmp)(const void *,const void *));
//base:首地址
//nelem:元素个数
//width:元素的大小
//最后一个是函数指针,指向比较函数
#include<stdlib.h>
int cmp(const void* a,const void* b)
{
//返回值有0,1,-1
//当*a<*b 返回1,*a>*b,返回-1,*a==*b,返回0时,是升序排序
}
int a[4]={1,2,4,3};
qsort(a,4,sizeof(int),cmp);
5.带头结点的List的reverse
void reverseList(node* head)
{
node* p=head->next;
if(!p)return;
node* q=p->next;
if(!q)return;
p->next=NULL;
while(q)
{
node* temp=q->next;
q->next=p;
p=q;
q=temp;
}
head->next=p;
}
6.创建带头结点的List的两种方法node* head;
createList(&head);
void createList(node** head)
{
*head=new node;
(*head)->next=NULL;
}//先创建一个头结点指针,然后将指针作为参数传递给create函数创建,这样由于不能被销毁,顾要用到双指针,而且函数内部写法复杂,不建议采用
node* head=createList();
node* createList()
{
node* head=new node;
head->next=NULL;
return head;
}//这种方法利用返回值传递头结点的指针,函数内部写法清楚明了
7.检测内存是否泄漏函数_CtrDumpMemoryLeaks();
printf("%7.4f\n",a[0]);打印一个浮点数a[0],%7.4f解释如下:
- 7:此浮点数的占的总位数(小数点算一位)
- 4:小数点后面显示的位数
- f:表示打印的是浮点数
9.函数参数不固定时如何处理函数参数
#include<stdarg.h>
va_list argp; //定义指向参数的指针argp
va_start(argp,msg)//设置argp的值,其指向参数msg后面的一个参数,msg是最后一个参数时,其就指向msg
// 具体的取arg过程。
char* p
p=va_arg(argp,char*)//返回argp指向的参数,参数的类型是char*。存储其时可以设置一个char*变量
char buffer[512];
vsprintf(buffer,format,argp)//与上面一样,都是将argp所指参数赋值给其他变量来处理。
va_end(argp)//设置argp=0;
10.string a="abc"的理解
string str=“abc”;
//实际就是调用string str("abc");并非运算符重载//c++ primer :implict conversion
//c类型的字符串如"abc"实际就是char*
//下面的代码就可以说明问题了
#include<stdio.h>
class String{
public:
String(char *p)
{
printf("Call String construcor\n");
}
void operator = (char *p)
{
printf("Call operator =\n");
}
};
int main()
{
String s = "abc";//输出Call String construcor
s = "abc";//输出Call operator =
return 0;
}
10. freopen的使用。其作用是重定向输入输出流。当有输入输出流对象时,其输入输出的定向被重新定向
在console程序中,输入输出流都是定向到console的,可以通过freopen("fileName","r",stdin)来从定性输入流为文件。通过freopen("fileName","w",stdout)来重定向输出流到文件。
当想让输入输出流从文件转到console中时,可以使用freopen("CON","r",stdin),freopen("CON","w",stdout) 来实现.
11.计算x^y的高效的算法
LL exp_mod(LL x,LL y){
LL ret=1;
while(y){
if(y&1) ret=(ret*x);
x=(x*x);
y=y>>1;
}
return ret;
}