C++基礎 筆記

 

1. 輸出固定位數ios

#include <iostream>
#include <iomanip>
using namespace std;
int main(){
    double amount = 8.0/5.0;
    cout<<amount<<endl;
    cout <<setprecision (0)<< fixed<<amount <<endl;
    cout<<amount+0.9<<endl;
    cout << setprecision (1)<<amount<<endl;
    cout <<setprecision (2)<<amount<<endl;

    system("pause");
return 0;
}

fixed 表示固定輸出格式。c++

setprecision(0) 是小數點後爲0位,四捨五入。git

2. 開方windows

#include <math.h>數組

cout<<sqrt(2.0)<<endl;dom

c++ 與 C 是兼容的 math.h 是C 中的 頭文件函數

3.  PIui

#include <math.h>
#defined _USE_MATH_DEFINES
...
cout<<"M_PI is "<<M_PI<<endl;

const double pi = 4.0*atan(1.0);
cout<<"pi is "<<setprecision(10)<<pi<<endl;

4. 輸出格式spa

%03d---一種左邊補0 的等寬格式,好比數字12,%03d出來就是: 012操作系統

//setw(n) 輸出寬度
cout<<setw(5)<<999<<endl;//[space][space]999

//setfill('c') 輸出寬度不足時填充
//setbase(int n) 轉換爲n 進制
cout<<setbase(8)<<999<<endl;

//hex %X, oct %o, dec %d
cout<<hex<<99<<endl;

5.用兩個元素的交換法
a = a+b;

b = a-b;

a= a-b;

 

6.判斷是否爲整數

if(floor(m+0.5)==m)

floor(m)返回 m 的整數部分,由於浮點數的運算有可能存在偏差,好比1變成了0.9999...因此floor的值會變成0

7.計時函數

#include<time.h>
...
printf("Time used = %.21f\n",(double)clock()/CLOCKS_PER_SEC);

 

8.cin的返回值

正常讀入返回 cin對象,不然返回0

輸入完畢須要enter, ctrl+z,enter

爲何還有第二個enter?

 

9. 關於文件讀入和標準輸出

重定向的方法:

#define LOCAL
...
#ifdef LOCAL
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif

更好的是在編譯選項而不是程序裏定義LOCAL符號。
怎麼定義?

不使用重定向:

FILE *fin,*fout;
fin = fopen("data.in","rb");
fout = fopen("data.out","wb");
int x;
fscanf(fin,"%d",&x);
fprintf(fout,"%d",x);
fclose(fin);
fclose(fout);

 c++:

#include<fstream>
using namespace std;
ifstream fin("aplusb.in");
ofstream fout("aplusb.out");

...
int a, b;
fin>>a>>b;
fcout<<a+b<<endl;

 

10. 整數範圍

int -2^31 ~ 2^31-1  略寬 -2*10^9 ~ 2*10^9

long long  -2^63 ~ 2^63-1 略窄 -10^19 ~ 10^19

 

11.頭文件

C++中保留着C語言的經常使用頭文件。能夠直接用。地道一點的話去掉擴展名.h 在前面加上c

如:stdio.h -> cstdio

12.數組

比較大的數組聲明應該儘可能在main 的外面 爲何?

 

#define MAXN 100+10//+10是爲了保險
int a[MAXN];

int main()
{
...
}

數組複製:

int a[10]={1,2,3,4,5,6,7,8,9,10};
int b[10];
memcpy(b,a,sizeof(int)*10); //10是拷貝的個數
cout<<b[4]<<endl;

//初始化數組

memset(b,0,sizeof(b));

 

13.字符數組

sprintf 輸出到字符串

#include<string.h>

char buf[99];
sprintf(buf,"%d%d%d%d",1,2,3,4);

for(int i=0;i<strlen(buf);i++){
if(strchr(s,buf[i])==NULL) 
...
}

strchr 返回第一個爲s的index

 

14.讀入字符串

fgetc(fin) 從打開的文件fin中讀取一個字符

標準輸入用:getchar()

返回值是int, 應該當肯定不是EOF時把它轉換成char

不一樣操做系統的回車換行符是不一致的:

windows: \r\n

Linus:\n

MacOS \r

fgets(buf,MAXN,fin)讀取完整一行放在字符數組buf中

ctype.h

isalpha(c)判斷是否爲字母

isdigit(c) 是否爲數字

isprint(c) 是否爲符號

toupper(c)返回大學形式

 

15. 結構體

struct Point{double x,y;};

struct Point a;

or

typedef struct{double x, y;}Point;

Point a;

16.判斷素數,簡便的方法

int is_prime(int x)
{
int i; //i 要從2開始,不然誤判1爲非素數
for(i=2;i*i<=x;i++)//只要考慮 sqrt(x)如下
    if(x%i==0) return 0;

return 1;

}

進一步的避免重複計算i*i 和 x 傳入負數

#include<assert.h>
int is_prime(int x)
{
    int i,m;
    assert(x>=0);
    if(x==1) return 0;
    m=floor(sqrt(x)+0.5);
    for(i=2;i<=m;i++)
    {
        if(x%i==0) return 0;
        return 1;
    }

}

當 x<0 會異常退出,是否也是不可取的?

 

17. char[][] 和 char[]排序

int m_compare(const void* first, const void* second){
    char* a = (char*)first;
    char* b = (char*) second;
    return strcmp(a,b);
}
int m_compare2(const void* first,const void* second){
    char* a = (char*) first;
    char* b = (char*) second;
    return *a-*b;

}
...
char dict[MAX_IN][8], sortDict[MAX_IN][8];
...
qsort(dict,i,sizeof(dict[0]),m_compare);
qsort(sortDict[j],strlen(sortDict[j]),sizeof(char),m_compare2);
用 法: void qsort(void *base,int nelem,int width,int (*fcmp)(const void *,const void *));
參數: 1 待排序 數組首地址
2 數組中待排序元素數量
3 各元素的佔用空間大小
4 指向函數的 指針,用於肯定排序的順序
 
18. 隊列
#include<queue>

queue<int>q;
q.push(1);
cout<<q.front()<<endl;
q.pop();
cout<<q.empty()<<endl;

19.stack

#include<stack>
stack<int> s;
s.push(1);
s.top(); //not same with queue, is TOP
s.pop();
s.empty();

20. 產生隨機數

#include<stdlib.h>
#include<time.h>

double random(){
    return (double)rand()/RAND_MAX;

}//generate [0,1]

int random(int m){
    return (int)(random()*(m-1)+0.5)

}//generate [0,m-1]


//use
srand(time(NULL));
int x=random(10);

rand()%n //notice the n's range, RAND_MAX is >=32767

 21. quick sort

#include <iostream>
using namespace std;
void Qsort(int a[],int low,int high)
{
    if(low >= high){
        return;
    }
    int first = low;
    int last = high;
    int key = a[first];
    while(first < last)
    {
        while(first < last && a[last]>=key)
            --last;
        a[first] = a[last];

        while(first<last && a[first]<=key)
            ++first;
        a[last] = a[first];
    }
    a[first] =key;
    

    Qsort(a,low,first -1);
    Qsort(a,last+1,high);


}


int main()
{
    int a[]={57,68,59,52,72,28,96,33,24};
    Qsort(a,0,sizeof(a)/sizeof(a[0])-1);//need minus 1
    for(int i=0;i<9;i++)
    {cout<<a[i]<<" ";}

    system("pause");
    return 0;
}

 

 22. binary search

int lower_bound(int* A,int x, int y, int v)
{
int m;
while(x<y)
{
m= x+(y-x)/2;
if(A[m] >=v) y=m;
else
x=m+1;

}
return x;

}

23. STL sort, lower_bound, upper_bound

int a[]={57,68,59,52,72,28,96,33,24};
sort(a,a+9);

for(int i=0;i<9;i++)
{cout<<a[i]<<" ";}

cout<<endl<<"upper bound "<<upper_bound(a,a+9,52)-a<<endl;//return 4
cout<<endl<<"lower bound "<<lower_bound(a,a+9,52)-a<<endl; //return 3
int myints[] = {1, 2, 3, 3, 4, 6, 7};
    vector<int> v(myints,myints+7);
    vector<int>::iterator low,up;

    sort (v.begin(), v.end());

    low=lower_bound (v.begin(), v.end(), 5);          ^
    up= upper_bound (v.begin(), v.end(), 20);                   ^

    cout << "lower_bound at position " << int(low- v.begin()) << endl;
    cout << "upper_bound at position " << int(up - v.begin()) << endl;
相關文章
相關標籤/搜索