C++常见的刷题实用函数

168 阅读1分钟

👉 “Offer 驾到,掘友接招!我正在参与2022春招打卡活动点击查看 活动详情

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

C++常见的刷题实用函数

  • next_permutation()
#include <iostream>   
#include <algorithm>    
using namespace std;

int main () {
    vector<int> v{1,2,3};
    do {
        cout << v[0] << ' ' << v[1] << ' ' << v[2] << '\n';
    } while ( next_permutation(v.begin(), v.end()) );
    return 0;
}
/* output:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
*/
  • prev_permutation() 输出所有比当前排列小的排列,顺序是从大到小

  • accumulate()

    • 定义在#include<numeric>中,作用有两个,一个是累加求和,另一个是自定义类型数据的处理
    • accumulate带有三个形参:头两个形参指定要累加的元素范围,第三个形参则是累加的初值\
#include <iostream>
#include <string>
#include <numeric>
#include <functional>
using namespace std;

int main(){
    vector<int> v{1,2,3};
    int i_sum = accumulate(v.begin(), v.end(), 0);
    vector<string> vs { "aa", "bb", "cc"};
    string s_sum = accumulate(vs.begin(), vs.end(), string(""));
    //求异或 同理还有bit_and  bit_or 
    int xor_sum = accumulate(v.begin(), v.end(), 0, bit_xor<int>());
    cout << i_sum << endl;
    cout << s_sum << endl;
    cout << xor_sum << endl;
    return 0;
}
/*
output:
6
aabbcc
0
*/
  • max_element() / min_element 求最大最小值
  • 离散化小技巧,查找索引
#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    vector<int> v{1,3,2,1000,300,5,4};
    sort(v.begin(),v.end()); //如果逆序排序:sort(v.rbegin(),v.rend());
    int m = unique(v.begin(), v.end()) - v.begin();
    for(int i = 0; i < m; i++) {
        int index = lower_bound(v.begin(), v.end(), v[i]) - v.begin();
        cout << v[i] << " : " << index << endl;
    }
        
    return 0;
}
/*
1 : 0
2 : 1
3 : 2
4 : 3
5 : 4
300 : 5
1000 : 6
*/
  • 随机数相关用法
#include <iostream>
#include <random>
using namespace std;
​
int main(){
    //生成 0到9之间均匀分布的随机数
    uniform_int_distribution<unsigned> u(0,9);
    default_random_engine e;    //生成无符号随机整数
    for (int i = 0; i < 10; i++)
        cout << u(e) << " ";  // 每个调用返回在指定范围内并服从均匀分布的值
    return 0;
}
/*
0 1 7 4 5 2 0 6 6 9 
*/

哈希表, 自定义键值类型

unordered_mapkey值如果是自定义类,需要为其定制hash函数:

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
​
class Student{
public:
    string name;
    int age;
    Student(string n, int a){
        name = n;
        age = a;
    }
    bool operator==(const Student & p) const 
    {
        return name == p.name && age == p.age;
    }
};
//重载operator()的类,将哈希函数打包成可以直接调用的类
struct my_hash{
    size_t operator()(const Student & p) const{
        return hash<string>()(p.name) ^ hash<int>()(p.age);
    }
};
​
int main(){
    unordered_map<Student, int, my_hash> mp;  //传入my_hash
    mp[Student("Mark", 18)] = 123;
    mp[Student("Andrew",20)] = 456;
    for ( auto [key, value] : mp ) {
        cout << key.name << " " << key.age << " " << value << endl;
    }
    return 0;
}