Map与Unordered_map的区别?
map:基于红黑树,元素有序存储
unordered_map:基于散列表,元素无序存储
在需要元素有序性或者对单次查询性能要求较为敏感时,请使用map,其余情况下应使用unordered_map,算法中更多的使用unordered_map。
Set与Map的区别?
点击进入查看详细
HashMap使用方法
首先导入库(map)及定义
1 2 3 4 5 6 7 8
| #include <iostream> #include <map>
using namespace std;
int main(){ map<int, string> hashmap; }
|
插入元素
1 2 3 4 5 6
| hashmap.insert(pair<int,string>(1,"这是1"));
hashmap.insert(map<int,string>::value_type (2,"这是2"));
hashmap[3] = "这是3";
|
遍历元素(C++ 11)
1 2 3
| for(auto i : hashmap){ cout << i.first << " " << i.second << endl; }
|
其中i.first返回的是key值,i.second返回的是key值对应的value值。
HashMap(unordered_map)使用方法
首先导入库
1 2 3 4 5 6 7 8
| #include <iostream> #include <unordered_map>
using namespace std;
int main(){ unordered_map<int,string> umap; }
|
插入元素、遍历(方法相同,点击跳转)
HashSet使用方法
首先导入库(set)与定义
1 2 3 4 5 6 7 8
| #include <iostream> #include <set>
using namespace std;
int main(){ set<char> set1; }
|
插入元素
1 2 3 4
| for(char c : TestCase){ set1.insert(c); }
|
遍历数组
1 2 3
| for(auto c : set1){ cout << c; }
|
此时会发现输出了“Helo”,Set作用之一便是去重。
HashSet(unorderd_set)使用方法
导入库与定义
1 2 3 4 5 6 7 8
| #include <iostream> #include <unorderd_set>
using namespace std;
int main(){ unorderd_set<char> uset; }
|