您的位置:首页 > 其它

STL学习

2016-06-27 00:05 387 查看
额,,,这是一个学了那么久 C++ 还不会用 STL 的老年选手(是时候退役啦。。。

虽然好像还是不会2333

不是说好的pkusc的时候学么2333

map

map的构造:
map <int,char> mp


元素的添加:
mp[1] = 'a'


map的大小:
mp.size()


map的删除:

mp.erase(x)
删除某个元素

mp.clear()
清空所有元素

ex.

#include<iostream>
#include<map>
using namespace std;

map <int,char> mp;

int main()
{
cout << (int)mp[2] << endl;
cout << mp.size() << endl;

return 0;
}


输出结果:

0
1


#include<iostream>
#include<map>
using namespace std;

map <int,int> mp;

int main()
{
mp[1] = 11;mp.insert(pair <int,int> (1,10));
cout << mp[1] << endl;

return 0;
}


输出结果:

11


map的遍历:

前向迭代器

#include<iostream>
#include<map>
using namespace std;

map <int,char> mp;
map <int,char> :: iterator it;

int main()
{
mp[2] = 'b',mp[1] = 'a',mp[3] = 'c';
for (it = mp.begin();it != mp.end();it ++)
cout << it -> first << ' ' << it -> second << endl;

return 0;
}


反向迭代器

#include<iostream>
#include<map>
using namespace std;

map <int,char> mp;
map <int,char> :: reverse_iterator it;

int main()
{
mp[2] = 'b',mp[1] = 'a',mp[3] = 'c';
for (it = mp.rbegin();it != mp.rend();it ++)
cout << it -> first << ' ' << it -> second << endl;

return 0;
}


mp.lower_bound(x)
: 返回不小于 x 的第一个位置

mp.upper_bound(x)
: 返回大于 x 的第一个位置

返回的是迭代器

#include<iostream>
#include<map>
using namespace std;

map <int,int> mp;

int main()
{
mp[1] = 11,mp[5] = 15,mp[9] = 19;
cout << mp.lower_bound(5) -> second << endl;

return 0;
}


输出结果

15


#include<iostream>
#include<map>
using namespace std;

map <int,int> mp;

int main()
{
mp[1] = 11,mp[5] = 15,mp[9] = 19;
cout << mp.upper_bound(5) -> second << endl;

return 0;
}


输出结果

19


set

set 元素不可重复

multiset 元素可重复

遍历

#include<iostream>
#include<set>
using namespace std;

set <int> S;
set <int> :: iterator it;

int main()
{
S.insert(5),S.insert(6),S.insert(-1);
for (it = S.begin();it != S.end();it ++)
cout << *it << endl;

return 0;
}


S.count(x)
S 中 x 的个数

S.clear()
将S清空

S.erase(x)
将S里的所有x删除

S.erase(S.find(x))
删除S里的一个x

vector

添加元素:
vec.push_back(x)


容器大小:
vec.size()


清空容器:
vec.clear()


在第 i 个位置添加元素 x:
vec.insert(vec.begin() + i,x)


删除第 i 个位置的元素:
vec.erase(vec.begin() + i,x)


ex.

#include<iostream>
#include<vector>
using namespace std;

vector <int> vec;
vector <int> :: iterator it;

int main()
{
vec.push_back(12),vec.push_back(8);
vec.insert(vec.begin() + 1,5);
for (it = vec.begin();it != vec.end();it ++)
cout << *it << endl;

return 0;
}


输出结果

12
5
8


排序:
sort(vec.begin(),vec.end(),comp)


翻转:
reverse(vec.begin(),vec.end())


bitset

functionsinstructions
b.any()是否存在为 1 的位置
b.none()是否全是 0
b.all()是否全是 1
b.count()有多少位置为 1
b.size()b的大小
b.set()将 b 中所有元素全置为 1
b.reset()将 b 中所有元素全置为 0
b.flip()将 b 逐位翻转
to_ulong转换为unsigned int
to_ullong转换为unsigned long long

queue

priority_queue 默认大根堆

functionsinstructions
q.pop()删除堆顶元素
q.top()取堆顶元素
q.push()加入一个元素
q.empty()q是否为空
q.size()q的大小
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: