1.set和unordered_set的
①插入
②读取
③删除
④创建一个降序set
这俩都是键不重复的集合,有序无序顾名思义。
使用erase(迭代器=find());删除一个键
使用*find(键号);访问对应键
#include<iostream>
#include<set>
#include<unordered_set>
using namespace std;
int main()
{
set<int>st;
unordered_set<int> ust;
set<int, greater<int> > dst;
st.insert(6);
st.insert(5);
st.insert(10);
st.insert(2);
cout << *st.find(2)<<endl;
st.erase(st.find(2));
cout << "set:" << endl;
for (set<int>::iterator it = st.begin(); it != st.end(); it++)
cout << *it << " ";
cout << endl;
ust.insert(6);
ust.insert(5);
ust.insert(10);
ust.insert(2);
cout << "unordered_set:" << endl;
for (unordered_set<int>::iterator it = ust.begin(); it != ust.end(); it++)
cout << *it << " ";
cout << endl;
dst.insert(6);
dst.insert(5);
dst.insert(10);
dst.insert(2);
cout << "d-unordered_set:" << endl;
for (set<int>::iterator it = dst.begin(); it != dst.end(); it++)
cout << *it << " ";
cout << endl;
return 0;
}
1.map和unordered_map的
①插入
②读取
③删除
④创建一个降序map
⑤查询一个键的值
这俩都是键不重复的集合,有序无序顾名思义。
使用erase(迭代器=find());删除一个键值对
使用find(键号)->second;访问对应键的值
如果是放入新数据,用数组下标的话会固定元素的位置 mp[1]=10;
如果需要自动排序的话,使用map,并且插入元素的时候使用
mp.insert(make_pair(1,10));
用这种方式插入的元素会自动进行升序排序
访问元素的时候也要注意,如果使用下标访问,如果访问到没有值的下标,那么会自动创建并且给予0的初值。
因此,访问元素的时候使用迭代器,才能正常的访问元素。
#include<iostream>
#include<set>
#include<unordered_set>
#include<map>
#include<unordered_map>
#include<string>
using namespace std;
int main() {
map<int, string> mp;
unordered_map<int, string> ump;
map<int, string, greater<int>> dmp;
mp.insert(make_pair(10, "s"));
mp.insert(make_pair(5, "a"));
mp.insert(make_pair(8, "g"));
mp.insert(make_pair(2, "d"));
ump.insert(make_pair(10, "s"));
ump.insert(make_pair(5, "a"));
ump.insert(make_pair(8, "g"));
ump.insert(make_pair(2, "d"));
dmp.insert(make_pair(10, "s"));
dmp.insert(make_pair(5, "a"));
dmp.insert(make_pair(8, "g"));
dmp.insert(make_pair(2, "d"));
cout << "mp.find(2):" << mp.find(2)->second << endl;
mp.erase(mp.find(2));
cout << "map:" << endl;
for (map<int, string>::iterator it = mp.begin(); it != mp.end(); it++) {
cout << it->first << " " << it->second;
cout << endl;
}
cout << endl;
cout << "unordered_map:" << endl;
for (unordered_map<int, string>::iterator it = ump.begin(); it != ump.end(); it++) {
cout << it->first << " " << it->second;
cout << endl;
}
cout << endl;
cout << "d-map:" << endl;
for (map<int,string >::iterator it = dmp.begin(); it != dmp.end(); it++) {
cout << it->first << " " << it->second;
cout << endl;
}
cout << endl;
return 0;
}