C++中刷题常用的一些函数记录(持续更新)

字符串相关操作

substr 字符串子串函数

string s("12345asdf");
string a = s.substr(0,5);     //获得字符串s中从第0位开始的长度为5的字符串

字符串反转

#include <algorithm>
std::string s = "abcde";
std::reverse(s.begin(), s.end());

字符串转数字

string s = "123";
int n = strtol(s.c_str(), nullptr, 10);

计算相关工具

求较大/小的数

#include <algorithm>
max(a, b);
min(a, b);

计算幂

# include <cmath>
int n = pow(2,3); //计算2的3次方

求绝对值

#include <algorithm>
int a = -1;
int b = abs(a);

集合相关操作

初始化

vector<int> v1{1,2,3};
vector<int> v2(3);	//创建长度为3的向量,元素默认全0

//初始化特定长度的二维向量
vector<vector<int>> ret(3);	
for(int i=0;i<3;i++){
    ret[i] = vector<int>(3);
}

//初始化二维向量,并赋初始值
auto f = vector<vector<int> >(m, vector<int>(m + 1, false));

排序算法

#include <algorithm>
vector<int> myVector{1,4,23,5,8,2};
sort(myVector.begin(), myVector.end());

自定义排序函数

class Student {
public:
    int number;
    Student(int num) {
        number = num;
    }
};
class Compare {
public:
    bool operator()(const Student &a, const Student &b) {
        return a.number < b.number;
    }
};
bool cmp(const Student &a, const Student &b) {
    return a.number < b.number;
}


Student s1(4);
Student s2(2);
Student s3(7);
vector<Student> v{s1, s2, s3};
sort(v.begin(), v.end(), cmp);	//方法一
sort(v.begin(), v.end(), Compare());	//方法二

元素位置各类调整

#incluede <algorithm>
vector<int> v{1,3,2};
swap(v[0], v[1]);	//调换位置
reverse(v.begin(), v.end())	//反转

从头插入

vector<int> v = {1, 2};
v.insert(v.begin(), 0);

使用迭代器访问元素

vector<int> v{1,3,2};
auto iterator = v.begin();
while (iterator!=v.end()){
    cout<<*iterator<<endl;
    iterator++;
}

删除(erase函数)

iterator = v.begin();
while (iterator!=v.end()){
    if(*iterator == 8){
        iterator = v.erase(iterator);
    } else{
        iterator++;
    }
}

去重(unique函数)

vector<int> v{1, 4, 23, 2, 23, 5, 8, 2};
sort(v.begin(), v.end());
auto it = unique(v.begin(), v.end());
v.erase(it, v.end());

unique函数可以将特定范围内,相邻重复的元素一起挪到集合的最后,并且返回重合元素的第一个迭代器位置。unique函数配合erase函数可以实现集合中元素的去重。

set的用法

set<int> s;   
int x = 1;
s.insert(x);    //插入
s.erase(x);     //删除,返回0或1,0表示set中不存在x
s.clear();      //清空
s.find(x);      //返回x的迭代器,如果x不存在,则返回s.end()

各种构造或初始化

  • 使用初始化列表的构造函数
    类名::类名(形参表):内嵌对象1(形参表),内嵌对象2(形参表)… { 类的初始化 }
    例如
class Circle {
public:
        Circle(float r):radius(r){}	//采用初始化列表的构造函数
private:
        float radius;
};

各种集合类的初始化声明

vector<int> v{1,2,3};	//向量的初始化
map<string, int> m{		//字典的初始化
	{"a", 1},
	{"b", 2},
	{"c", 3}
};
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值