1.Vector
1.1 definition
变长数组
//一维变长数组
vector <typename> name
//二维变长数组
vector <typename> name[ArraySize]
1.2 vector元素的访问
- 通过下标访问
- 通过迭代器访问
iterator的定义是,类似指针的东西
vector <typename> :: iterator it;
The following is example:
//vi是vector向量
vector <int> :: iterator it=vi.begin();
for (int i=0;i<5;i++){
cout<<*(it)<<" ";
it++;
}
注意:一般只有vector和string才允许使用 vi.begin()+3这样的iterator+整数的写法。
1.3 The functions of Vector
- push_back()
- pop_back()
- size()
- clear()
- insert()
// inserting into a vector
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector (3,100);
std::vector<int>::iterator it;
it = myvector.begin();
it = myvector.insert ( it , 200 );
myvector.insert (it,2,300);
// "it" no longer valid, get a new one:
it = myvector.begin();
std::vector<int> anothervector (2,400);
myvector.insert (it+2,anothervector.begin(),anothervector.end());
int myarray [] = { 501,502,503 };
myvector.insert (myvector.begin(), myarray, myarray+3);
std::cout << "myvector contains:";
for (it=myvector.begin(); it<myvector.end(); it++)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Output:
myvector contains: 501 502 503 300 300 400 400 200 100 100 100
- erase()
erase(it)删除iterator it 的元素
erase(first, last); //删除[ first, last )的元素
1.4常见用途
- 存储数据
- 图的邻接表存储
1.5 vector可以通过输入数来确定一个数组的动态大小
例如下面这段代码:
int main() {
int n;
cin >> n;
vector<int> record(n,3); //record长度为n,元素预置为3
for (int i = 0; i < record.size(); i++)
cout << record[i] << " ";
return 0;
}
对于c++,我们完全可以充分利用它自己强大而方便的容器,比如vector,之所以动态声明数组,相比是大小不确定,声明太大了怕浪费空间,而vector就不用指定大小,当存的数据变多,自动扩大容量,比如假设vector默认大小是8,当你再往里存第9个元素时,容器自动扩容,变为16,16再不够用,扩为32,2倍2倍的增长,这样就根据需要扩容,不会浪费空间,也可以像普通数组那样直接指定vector的大小,总之普通数组可以的它都可以,普通数组没有的它更有;
一维:
vector a;
a.push_back(k);
k为待存入数组的数,用法一样,可以a[i]这样直接取数,还有各种自带的方法,使用方便极了
vector a;
vector a(5); //指定数组大小是5
vector a(5,3); //数组大小为5,并初始化数组所有元素值为3
二维:
cin>>m>>n;//m行n列
vector<vector > a(m, vector(n)); //这行注意两个> >中间要加空格,否则会被认为是重载>>运算符
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
a[i][j] = i*j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
cout<<a[i][j]<<’ ';
cout<<endl;
2.set
definition
内部自动有序而且不含重复元素
有序是从小到大
set <typename> name;
//set数组
set <typename> Arrayname[arraysize];
访问
set只能通过迭代器访问
set <typename> :: iterator it;
#include <iostream>
#include <string>
#include <stdio.h>
#include <set>
using namespace std;
int main() {
set <int> st;
set <int> ::iterator it;
for (int i = 0; i > -9; i = i - 2) {
st.insert(i);
}
st.insert(0);
//不支持it<st.end();
//st.end()指向:最后一个元素+1
for (it = st.begin(); it != st.end(); it++) {
cout << *it<<" ";
}
return 0;
}
/*
输出:-8 -6 -4 -2 0
*/
The functions of Set
- insert(); //O(logN)
- find(value); //O(logN), return the iterator
- erase();
st.erase(it); //delete the *it
st.erase(value); //删除值为value的元素,O(logN)
st.erase(first_it,last_it); //delete the element [f,l), f,l are iterators
- size();
- clear();
3.String
3.1 defination
- 定义
#inlcude <string>
using namespace std;
string str="abcd";
- 输入输出:
读入和输出整个字符串,只能使用cin/cout.
int main() {
string str;
cin >> str;
cin >> str;
if(cin.get()==' ') //第三个字符串为空格才会输出
cout << str<<endl;
printf("%s\n", str.c_str()); //将string变成字符数组
return 0;
/*
输入:scs scsa <-空格
输出:scsa
scsa
*/
}
3.2 访问
- 通过下标访问
- 通过iterator访问
cout<<*it; //即可输出it指向的字符 - 可以使用str.c_str(),即可printf输出
void main()
{
string aa="qqq";
printf("%s",aa.c_str()); //不推荐
//或者cout<<a;
}
3.3 The functions of String
- operator +=
int main() {
string str1,str2;
str1 = "abc";
str2 = "def";
str1 = str1 + str2;
cout << str1 << endl;
return 0;
}
-
compare operator
两个string可以用==, !=, < , >, >=比较,规则是字典序。 -
size();
返回元素个数 -
insert();
insert(pos, string); //在pos处插入string
insert(it, it2, it3 ); //串[it2, it3)被插在it上。
- erase();
str.erase(it); //delete the *it
str.erase(first_it,last_it); //delete the element [f,l), f,l are iterators
str.erase(pos,length); //pos 为起始位置,length为删除字符个数
- clear();
- substr();
返回从pos开始,长度为len的子串
s.substr(); // 返回s的全部内容
s.substr(11); // 从索引11往后的子串
s.substr(5,6); // 从索引5开始6个字符
int main()
{
string s = "12345678";
string s1(s, 0, 3),s2=s.substr(0,3);
cout << s1 << endl;
cout << s2 << endl;
return 0;
}
//result:
123
123
- string::npos;
string::npos=-1 - find();
//返回str2第一次在str中出现的位置,如果str2不是str的子串,返回string::npos
//时间复杂度O(mn)
str.find(str2);
- replace();
//把str从pos开始,长度为len的子串替换成str2
str.replace(pos,len,str2);
//把str的iterator [it1,it2)范围的子串替换成str2;
str.replace(it1,it2,str2);
3.3 把string按空格划分
C++ Split string into vector by space
参见:https://blog.youkuaiyun.com/qq_44761480/article/details/100542089
4.Map
4.1 defination
映射容器map是一种关联容器,表示的是对偶(键,值)的序列。它支持唯一Key类型的键值,并提供对另一个基于键的类型T的快速检索。map还提供双向迭代器。映射容器map在标准C++中,对应于map类,被定义在
映射:键→值,值 = 映射[键](似f:x → y,y = f(x))。即,可以通过映射,由键来快速定位值。
include<map>
map <typename1,typename2> mp;
map<string,int> mp; //字符串到整型,只能是string
map<set<int>,string> mp;
map内部默认按字典序排序,不过也可以修改(但是不太懂,感觉还是sort+结构体方便)。
#include <iostream>
#include <string>
#include <stdio.h>
#include <set>
#include<string>
#include <map>
#include<algorithm>
using namespace std;
//这个重载我还不太懂,建议不要轻易使用
struct ltstr
{
bool operator () (string s1, string s2) const
{
return s1>s2;
}
};
int main() {
map<string, int, ltstr> months;
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
months["april"] = 30;
months["may"] = 31;
months["june"] = 30;
months["july"] = 31;
months["august"] = 31;
months["september"] = 30;
months["october"] = 31;
months["november"] = 30;
months["december"] = 31;
map<string, int, ltstr>::iterator it;
cout << "通过iterator访问:" << endl;
for (it = months.begin(); it != months.end(); it++) {
cout << it->first << " " << it->second << endl;
}
cout << "通过下标访问:" << months["may"]<<endl;
return 0;
}
结果:
通过iterator访问:
september 30
october 31
november 30
may 31
march 31
june 30
july 31
january 31
february 28
december 31
august 31
april 30
通过下标访问:31
4.2 元素的访问
- 通过下标访问,注意key是唯一的
- 通过iterator访问
map<string, int, ltstr>::iterator it;
it->first可以访问key;it->second可以访问value;
4.3 Commonly used functions
- find();
O(logN)
find(key); //返回键为key的映射的iterator
Searches the container for an element with a key equivalent to k and returns an iterator to it if found, otherwise it returns an iterator to map::end.
// map::find
#include <iostream>
#include <map>
int main ()
{
std::map<char,int> mymap;
std::map<char,int>::iterator it;
mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;
it = mymap.find('b');
if (it != mymap.end())
mymap.erase (it);
// print content:
std::cout << "elements in mymap:" << '\n';
std::cout << "a => " << mymap.find('a')->second << '\n';
std::cout << "c => " << mymap.find('c')->second << '\n';
std::cout << "d => " << mymap.find('d')->second << '\n';
return 0;
}
output:
elements in mymap:
a => 50
c => 150
d => 200
- erase();
//delete the sigle element, matching with mp.find()
mp.erase(it); //it is the iterator. O(1)
mp.erase(key); //O(logN)
//delete the elements in [first,last)
mp.erase(first,last);
- size();
获取映射的个数 - clear();
清空所有元素
5. queue
5.1 defination
#include<queue>
queue<typename> name;
5.2 访问
由于队列先进先出,只能通过
q.front()访问首元素;即最早被压入队列的元素。
q.back()访问队尾元素;即最后被压入队列的元素。
5.3 Commonly used functions
- push();
- front(); back()
- pop();
- empty();
判断队列是否为空 - size();
6. priority_queue
底层是用堆实现的,队首元素一定是优先级最高的那个。
6.1 defination
#include<queue>
using namespace std;
priority_queue<typename> name
6.2 访问
只能通过top()函数访问队首元素
6.3 常见函数
- push();
- top();
- pop();
- empty();
6.4 priority_queue内优先级的设置
- 基本数据类型的优先级设定
默认状态下,一般数字/字典序大的优先级高
priority_queue<int> q;
priority_queue<int>, vector<int>, less<int> >q;
priority_queue<int>, vector<int>, greater<int> >q;
- 结构体或者其他STL容器的优先级设置
建议使用struct把cmp包装起来
#include <iostream>
#include <string>
#include <stdio.h>
#include <set>
#include<string>
#include <map>
#include<queue>
#include<algorithm>
using namespace std;
struct fruit {
string name;
int price;
};
struct cmp {
//可以改为 bool operator () (const fruit &f1, const fruit &f2) 提高速度
bool operator () (fruit f1, fruit f2) {
return f1.price > f2.price; //若返回ture, f2优先级大
}
};
int main() {
priority_queue<fruit, vector<fruit>, cmp> q;
fruit f1,f2,f3;
f1.name = "peach";
f1.price = 2;
f2.name = "banana";
f2.price = 4;
f3.name = "apple";
f3.price = 5;
q.push(f1);
q.push(f2);
q.push(f3);
cout << q.top().name << " " << q.top().price << endl;
return 0;
}
//结果
//peach 2
7.Stack
1 defination
后进先出
#include<stack>
stack<int> s;
2 访问
只能通过top();
3 Commonly used Functions
s.push();
s.top();
s.pop();
s.empty();
s.size();
8. pair
9.algorithm
#include< algorithm >
9.1 max(), min(), abs()
max(x, y);
min(x, y);
abs(x); //这里x必须为整数,浮点数请使用cmath下的fabs()。
9.2 swap()
swap(x,y);
9.3 reverse()
reverse(it, it2)可以将数组指针在[it, it2)之间的元素
或容器迭代器在[it,it2)范围的元素进行反转。
9.4 fill()
可以把数组或容器某一区段赋予相同的值;
int a[5]={1,2,3,4,5};
fill(a,a+3,223);
9.5 sort
defination
sort(首元素地址,尾元素地址的下一个地址,比较函数)
cmp函数的实现
bool cmp(int a,int b){
return a>b; //当a>b时把a放在b前面
}
可以对结构体排序
也可以对vector, string, deque排序