leetcode中经常使用的一些c++方法

本文详细介绍了C++中string类的substr方法、set和map的erase操作,以及vector的sort和erase,还涵盖了数组去重、字符串转换、查找函数和数据结构排序。涉及关键词包括字符串处理、数据结构、集合操作和算法应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.string.substr

s.substr(p, n)

返回一个string,包含字符串s中从p开始的n个字符的拷贝(p的默认值是0,n的默认值是s.size() - p,即不加参数会默认拷贝整个s)

2.set.erase

set<int> st;
st.insert(1);
st.insert(3);
st.erase(1);//直接删除
st.erase(st.find(3));//找到删除 区间这里不做表达

3.map.erase

map的erase方法有三种形式

(1)
 void erase (iterator position); 
(2)
 size_type erase (const key_type& k); 
(3)
 void erase (iterator first, iterator last);

第一种方式根据迭代器删除;

第二种方式根据key删除

第三种是指定迭代器范围,然后删除范围内所有

4.vector.sort

sort(s.begin(),s.end(),cmp)

如果是在类中定义cmp,则注意要定义cmp为静态方法(static)

5.string.erase

string.erase(pos,n)          //删除从pos开始的n个字符    string.erase(0,1);   删除第一个字符

string.erase(pos)           //删除pos处的一个字符(pos是string类型的迭代器)

6.vector中没有find函数

7.删除数组中的重复元素

vector<int> a;
sort(a.begin(),a.end());
auto it=unique(a.begin(),a.end());
a.erase(it,a.end());

8.字符串转数字

atoi,将字符数组转为数字,转换string的时候,要先将string转为字符数组(使用c_str()函数)

string s1="123";

cout<<atoi(s1.c_str())<<endl;

 9.数字转字符串

to_string(),将数字转为字符串

int a=1234;
cout<<to_string(a)<<endl;

10.str.find_first_not_of

str.find(str1):在str中寻找子串str1,返回该子串的起始索引位置

str.find_first_of(str1):在str中寻找子串str1,返回该子串的起始索引位置

str.find_last_of(str1):在str中寻找子串str1,返回该子串的最后一个字符的索引位置

str.find_first_not_of(str1):返回str中第一个不是str1的元素的位置

str.find_last_not_of(str1):返回str中最后一个不是str1的元素的位置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值