常用函式複習

本篇複習筆記主要介紹C++中常用函式的使用方式。

math函式

以下函式皆在 c語言<math.h> c++<cmath> 標頭檔中定義

pow

pow(x,y) 計算

xy之值。

#include<bits/stdc++.h> #define ll long long using namespace std; int main(){ double a,b; cin>>a>>b; cout<<pow(a,b)<<'\n'; return 0; }

sqrt

sqrt(x) 計算x平方根之值。

#include<bits/stdc++.h> #define ll long long using namespace std; int main(){ double a; cin>>a; cout<<sqrt(a)<<'\n'; return 0; }

abs

abs(x) 計算x之絕對值。

#include<bits/stdc++.h> #define ll long long using namespace std; int main(){ int a; cin>>a; cout<<abs(a)<<'\n'; return 0; }

__gcd

gcd(a,b) 計算a,b之最大公因數。

#include<bits/stdc++.h> #define ll long long using namespace std; int main(){ int a,b; cin>>a>>b; cout<<__gcd(a,b)<<'\n'; return 0; }

algotithm函式

以下函式皆在 <algorithm> 標頭檔中定義

sort

sort( begin,end,cmp) 從陣列的begin位置到end-1位置進行排列,排列方式為有小到大,可自行定義排列方式,時間複雜度為O(nlogn)。

#include<bits/stdc++.h> #define ll long long using namespace std; int a[100005]; vector<int> v(100005); bool cmp(int a,int b){ a>b; } int main(){ int n,x; cin>>n; for(int i=0;i<n;++i)cin>>a[i]; sort(a,a+n);//對array做排序 cin>>n; for(int i=0;i<n;++i)cin>>v[i]; sort(v.begin(),v.end());//對vector做排序 sort(a,a+n,cmp);//自定義排列 sort(a,a+n,[](int a,int b){ return a>b; });//以lambda函式自定義排列 return 0; }

max

max(a,b) 會比較其參數中傳遞的兩個數字,並返回兩個中較大的一個,如果兩個相等,則返回第一個。

#include<iostream> #include<algorithm> using namespace std; int main() { //回傳較大之參數 cout << max(1,2) << "\n"; //多筆參數比對 cout<< max({1,2,3,4})<<'\n'; return 0; }

min

min(a,b) 會比較其參數中傳遞的兩個數字,並返回兩個中較小的一個,如果兩個相等,則返回第一個。

#include<iostream> #include<algorithm> using namespace std; int main() { //回傳較大之參數 cout << min(1,2) << "\n"; //多筆參數比對 cout<< min({1,2,3,4})<<'\n'; return 0; }

fill

lower_bound

lower_bound( begin,end,num,greater() ) 從陣列的begin位置到end-1位置二分查詢第一個大於或等於num的數字,找到返回該數字的地址,不存在則返回end,此陣列需經過排序使其具有單調性,時間複雜度為O(logn)。

#include<bits/stdc++.h> #define ll long long using namespace std; int a[100005]; int main(){ int n,x; cin>>n; for(int i=0;i<n;++i)cin>>a[i]; sort(a,a+n); cin>>x; cout<<lower_bound(a,a+n,x)-a<<'\n'; //通過返回的地址減去起始地址begin,得到索引值 return 0; }

upper_bound

upper_bound( begin,end,num,greater() ) 從陣列的begin位置到end-1位置二分查詢第一個大於num的數字,找到返回該數字的地址,不存在則返回end,此陣列需經過排序使其具有單調性,時間複雜度為O(logn)。

#include<bits/stdc++.h> #define ll long long using namespace std; int a[100005]; int main(){ int n,x; cin>>n; for(int i=0;i<n;++i)cin>>a[i]; sort(a,a+n); cin>>x; cout<<upper_bound(a,a+n,x)-a<<'\n'; //通過返回的地址減去起始地址begin,得到索引值 return 0; }

binary_search( begin,end,num,greater() ):從陣列的begin位置到end-1位置二分查詢num是否存在陣列中,找到返回True,不存在則返回False,此陣列需經過排序使其具有單調性,時間複雜度為O(logn)。

#include<bits/stdc++.h> using namespace std; int a[100005]; int main() { int n,x; cin>>n; for(int i=0;i<n;++i)cin>>a[i]; cin>>x; if(binary_search(a,a+n, x)) cout << "found" <<'\n'; else cout << "not found" <<'\n'; return 0; }

string 函式

memset

memcpy