刷题常用函数
🍅 sort()
template< class RandomIt, class Compare >
constexpr void sort( RandomIt first, RandomIt last, Compare comp );
🍅 max()
template<class T, class Compare>
const T& max(const T& a, const T& b, Compare comp)
{
return (comp(a, b)) ? b : a;
}
🍅 accumulate()
有三个参数(前三个)和四个参数的版本
template<class InputIt, class T, class BinaryOperation>
constexpr // since C++20
T accumulate(InputIt first, InputIt last, T init, BinaryOperation op);
🍅 std::vector<T,Allocator>::insert
iterator insert( const_iterator pos, size_type count, const T& value );
template< class InputIt >
constexpr iterator insert( const_iterator pos, InputIt first, InputIt last );
🍅 std::vector<T,Allocator>::assign
例:
vector<int> nums{1,2,5,3,-9,5,3};
//非降序 非升序排序
sort(nums.begin(),nums.end());
sort(nums.begin(),nums.begin()+3,greater<>());
//两数间较大值
int max_num = max(2,3);
//累加, 基数为0
int sum = accumulate(nums.begin(),nums.begin()+4,0);
//累乘, 基数为1
int sum = accumulate(nums.begin(),nums.begin()+4,1,std::multiplies<int>());
//用于vector
//在迭代器指向的位置前插入一个2,返回新插入2的位置
auto it = nums.begin();
it = nums.insert(it,2); //2,1,2,5,3,-9,5,3
//插入3个2
nums.insert(it,2,5); //5,5,2,1,2,5,3,-9,5,3
//插入一段东西, 返回这一段东西的第一个元素的位置
vector<int>nums2(2,9);
nums.insert(it+1,nums2.begin(),nums2.end()); //5,9,9,5,2,1,2,5,3,-9,5,3
//替换内容
nums.assign(5,1); //1,1,1,1,1
nums.assign(nums2.begin(),nums2.end()); //9,9
计算时中常用到一些函数, 整理一下
<algorithm>
🗡️ 最大最小 max min
//可以输入int char double等
std::cout << "max(2,1)==" << std::max(2,1) << '\n';
std::cout << "max('a','z')==" << std::max('a','z') << '\n';
std::cout << "max(3.14,2.73)==" << std::max(3.14,2.73) << '\n';
🗡️ 更多
<cmath>
🗡️ 绝对值 abs
int i_c = abs(-29); //i_c = 29
🗡️ 向下/向上取整 cell
printf ( "ceil of 2.3 is %.1f\n", ceil(2.3) );//3
printf ( "floor of 3.8 is %.1lf\n", floor (-4.8) );//-4
🗡️ 开方 pow
printf ("7 ^ 3 = %f\n", pow (7.0, 3.0) );
🗡️ 开根号(1/2) sqrt
double param, result;
param = 1024.0;
result = sqrt (param);
printf ("sqrt(%f) = %f\n", param, result );
🗡️取对数 log(e为底) , log10(10为底)
double param, result;
param = 5.5;
result = log (param);
printf ("log(%f) = %f\n", param, result );
🗡️ 正弦 sin (用的弧度)
#define PI 3.14159265
double result;
result = sin (30*PI/180); //sin(π/6) = 1/2
🗡️ arccos acos(传double,返回double)
#define PI 3.14159265
double param, result;
param = 0.5;
result = acos (param) * 180.0 / PI;
printf ("The arc cosine of %f is %f degrees.\n", param, result);
其他
🗡️ 无穷大和无穷小
double max_d = DBL_MAX;
double min_d = DBL_MIN;
int max_i = INT_MAX;
int min_i = INT_MIN;