我查了查:
set和map底层是红黑树,unordered_set和unordered_map底层是哈希表。
底层 | |
---|---|
set,map | 红黑树 |
unordered_set,unordered_map | 哈希表 |
set和unordered_set,是集合,不能插入相同元素。
set以红黑树为底层,自动排序。
unordered_set以哈希表为底层,不会自动排序。
演示代码:
void test_set()
{
set<int> s;
s.insert(78);
s.insert(20);
s.insert(15);
s.insert(8);
s.insert(7);
s.insert(6);
cout << "set没有经过排序输出的内容:" << endl;
for (auto x : s)
{
cout << x << " ";
}
cout << endl;
}
void test_unordered_set()
{
unordered_set<int> s;
s.insert(78);
s.insert(20);
s.insert(15);
s.insert(8);
s.insert(7);
s.insert(6);
cout << "unordered_set(没有经过排序)输出的内容:" << endl;
for (auto x : s)
{
cout << x << " ";
}
cout << endl;
}
结果:
set会自动按照元素的值进行排序。
map和unordered_map
map以红黑树为底层,自动排序。
unordered_map以哈希表为底层,不会自动排序。
演示代码:
void test_map()
{
map<int, string> m;
m.insert(pair<int, string>(3, "three"));
m.insert(pair<int, string>(1, "one"));
m.insert(pair<int, string>(2, "two"));
cout << "map没有经过排序输出的内容:" << endl;
for (auto x : m)
{
cout << "key=" << x.first << ",key对应的value=" << x.second << "。\t";
}
cout << endl;
}
void test_unordered_map()
{
unordered_map<int, string> m;
m.insert(pair<int, string>(3, "three"));
m.insert(pair<int, string>(1, "one"));
m.insert(pair<int, string>(2, "two"));
cout << "unordered_map没有经过排序输出的内容:" << endl;
for (auto x : m)
{
cout << "key="<<x.first <<",key对应的value="<<x.second <<"。\t";
}
cout << endl;
}
结果:
map会自动按照key的值对元素进行排序。
共性:
set和map和unordered_map和unordered_set的相同之处在于,都不能插入相同的元素。
对set和unordered_set是不能插入值相同的元素,
代码修改为:
s.insert(78);
s.insert(8);
s.insert(8);
结果是:
对于map和unordered_map是不能插入key值相同的元素。
代码修改为:
m.insert(pair<int, string>(3, "three"));
m.insert(pair<int, string>(1, "one"));
m.insert(pair<int, string>(2, "two"));
m.insert(pair<int, string>(3, "three"));
m.insert(pair<int, string>(4, "three"));
结果是:
补充:
关于增强型for循环:
原本的for循环:
for(int i=0;i<n;i++)
{
······
}
增强型for循环:
for(数据类型/auto x:arr)
{
······
}
auto是C++的一个关键字,原理就是根据后面的值,来自己推测前面的类型是什么。
遍历容器时,使用这种写法很方便。