C++:一些常用函式的應用(更新ing)
C++中使用find函式查詢指定陣列中某個值的下標
find函式在< algorithm >庫中,使用時注意匯入。
find函式的定義如下所示:
_InputIterator find(_InputIterator __first, _InputIterator __last, const _Tp& __val)
引數中,第一個為陣列的起始位置,第二個為陣列的終點,可以這樣理解:
find[begin, end,val),在這個範圍內查詢val這個值,
注意要保證find值和查詢範圍值的資料型別統一
。它的返回型別是一個迭代器,與指標類似,這意味著我們不能直接把它作為下標來使用,但是用它減去_InputIterator __first就是我們需要的下標了。
2. 取整函式 ceil(),floor(), round()
#include
(1)使用
floor函式
,往下取值。floor(x)返回的是小於或等於x的最大整數。
如:floor(10。5) == 10 floor(-10。5) == -11
(2)使用
ceil函式
,往上取整。ceil(x)返回的是大於x的最小整數。
如:ceil(10。5) == 11 ceil(-10。5) ==-10
(3)使用
round函式
,四捨五入。round(x)返回的是x的四捨五入值。
如:ceil(10。6) == 11 ceil(-10。4) ==-10
3. pow()函式,即冪函式
#include
double pow( double base, double exp );
其中解釋如下:計算x的y次冪。返回值:x不能為負數且y為小數,或者x為0且y小於等於0,返回
冪指數
的結果。返回型別:double型,int,float會給與警告!
C++提供以下幾種
pow函式
的過載形式:
double pow(double X,int Y);
float pow(float X,float Y);
float pow(float X,int Y);
long double pow(long double X,long double Y);
long double pow(long double X,int Y);
4. copy()函式
#include< algorithm >
將 b[ ] 複製給 a[ ],格式如下:
copy( b。begin(), b。end(), a。begin() );
5. 指定區間隨機數
#include
srand((unsigned)time(null));
(low,up) #define Random (rand()%(up-low-1)) + 1 + low
[low,up) #define Random (rand()%(up-low)) + low
(low,up] #define Random (rand()%(up-low))+ low + 1
[low,up] #define Random (rand()%(up-low+1)) + low
意味:將Random定義成xxx。