set,map,unordered_set,unordered_map

我查了查:
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++的一个关键字,原理就是根据后面的值,来自己推测前面的类型是什么。
遍历容器时,使用这种写法很方便。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值