lc刷题常用函数总结(长期更新)

1.substr

获取某字符串的从某个位置开始固定长度的子串

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

2.stoi

把string转换为int

 string s = "123456";
    int k;
    k = stoi(s);  //k为123456

3.to_string
把int转换为string

 string pi = "pi is " + to_string(3.1415926);
    cout<<pi; //输出为pi is 3.141593

4.二维vector

vector<vector<int>> dp(n,vector<int>(n));

5.lower_bound( begin,end,num)
从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。

#include<iostream>
#include <vector>

using namespace std;

int main()
{
    
    
    vector<int> s= {
    
    1,3,5,7,9,11};
    auto it = lower_bound(s.begin(),s.end(),5);
    cout<<*it<<endl;
    auto  it1 = lower_bound(s.begin(),s.end(),6);
    cout<<*it1;
    
}

6.upper_bound( begin,end,num)
从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。

7.对于map的遍历

for(auto &[key,value] : map)

详见lc.677

8.边界易出错
如果一个二维数组的n,m都可以取0,那么不能定义长度用

int n = a.size();
int m =a[0].size();

9.map.count(n)

unordered_map::count()是C++中的内置方法,用于通过给定 key 对unordered_map中存在的元素数量进行计数。
注意:由于unordered_map不允许存储具有重复键的元素,因此count()函数本质上检查unordered_map中是否存在具有给定键的元素。

 unordered_map<int , string> umap; 
 umap.insert(make_pair(1,"Welcome")); 
 umap.insert(make_pair(2,"to")); 
 umap.insert(make_pair(3,"GeeksforGeeks")); 
 if(umap.count(1)) 
    {
    
     
        cout<<"Element Found"<<endl; 
    } 
    else
    {
    
     
        cout<<"Element Not Found"<<endl;     
    } 

10.copy函数
在两个容器之间复制元素:

int myints[] = {
    
    10, 20, 30, 40, 50, 60, 70};
vector myvector;
myvector.resize(7); // 为容器myvector分配空间
//copy用法
//将数组myints中的七个元素复制到myvector容器中
copy ( myints, myints+7, myvector.begin() );

猜你喜欢

转载自blog.csdn.net/qq_47997583/article/details/121213450
今日推荐