提前声明:这里的内容不是很多,也不是很全。不过用来刷LeetCode已经够用了。
文章目录
vector
初始化
vector<int> arr;
vector<int> arr(n);//容量为n
vector<int> arr(n,0);//容量为n,每个数为0
vector<int> arr(arr1.begin(),arr1.end());//拷贝一个vector
拼接两个vector
std::vector<int> v3;
v3.insert(v3.end(),v1.begin(),v1.end());
v3.insert(v3.end(),v2.begin(),v2.end());
增删
arr.push_back(1);
arr.pop_back();
反转
reverse(arr.begin(),arr.end());
查找元素
#include<algorithm>
if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
do_this();
else
do_that();
获取元素所在下标
int index = find(vec.begin(),vec.end(),value) - vec.begin();
map
初始化
map<int,int> mp;
mp[n] = xxx;
mp.insert(pair<int,int>(x,y));
查找
这里给出2种常用的数据查找方法。
第1种:用count函数来判断关键字是否出现,其缺点是无法定位数据出现的位置,由于map的一对一的映射特性,就决定了count函数的返回值只有两个,要么是0,要么是1,当要判断关键字出现时返回1.
第2种:用find函数来定位数据出现的位置,它返回一个迭代器,当数据出现时,它返回数据所在位置的迭代器;如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器。
queue
拷贝构造
queue<int> words;
std::queue<std::string> copy_words {words}; // A duplicate of words
API函数
queue 和 stack 有一些成员函数相似,但在一些情况下,工作方式有些不同:
front()
:返回 queue 中第一个元素的引用。如果 queue 是常量,就返回一个常引用;如果 queue 为空,返回值是未定义的。back()
:返回 queue 中最后一个元素的引用。如果 queue 是常量,就返回一个常引用;如果 queue 为空,返回值是未定义的。push(const T& obj)
:在 queue 的尾部添加一个元素的副本。这是通过调用底层容器的成员函数 push_back() 来完成的。push(T&& obj)
:以移动的方式在 queue 的尾部添加元素。这是通过调用底层容器的具有右值引用参数的成员函数 push_back() 来完成的。pop()
:删除 queue 中的第一个元素。size()
:返回 queue 中元素的个数。empty()
:如果 queue 中没有元素的话,返回 true。emplace()
:用传给 emplace() 的参数调用 T 的构造函数,在 queue 的尾部生成对象。swap(queue<T> &other_q)
:将当前 queue 中的元素和参数 queue 中的元素交换。它们需要包含相同类型的元素。也可以调用全局函数模板 swap() 来完成同样的操作。
优先队列 priority_queue
priority_queue<int> q;
升序队列
priority_queue <int,vector<int>,greater<int> > q;
降序队列
priority_queue <int,vector<int>,less<int> >q;
自定义排序队列
//对象
struct Node{
int f;
string c;
Node(int f,string c){
this->f = f;
this->c = c;
}
// bool operator<(const Node& a){
// return f < a.f;
// }
};
//重写比较方法
struct cmp{
bool operator() (Node* n1,Node* n2){
if(n1->f < n2->f){
return true;
}else if(n1->f > n2->f){
return false;
}else{
// n1->c.compare(n2->c);
return n1->c < n2->c;
}
}
};
//使用
priority_queue<Node*,vector<Node*>,cmp> q;
Node* temp = new Node(2,"coding");
q.push(temp);
q.push(new Node(4,"abcf"));
q.push(new Node(3,"abc"));
q.push(new Node(2,"leet"));
q.push(new Node(1,"a"));
q.push(new Node(4,"abcd"));
while(!q.empty()){
cout << q.top()->f <<" " << q.top()->c<< endl;
q.pop();
}
字符串
数字转化
C++11版本的to_string
string str = to_string(25);
反转
需引入 <algorithm>
reverse(s.begin(),s.end());
cout << s << endl;
截取
s.substr(pos, n) //截取s中从pos开始(包括0)的n个字符的子串,并返回
s.substr(pos) //截取s中从从pos开始(包括0)到末尾的所有字符的子串,并返回