集合概念、常用操作及实现

概念及常用操作

一般意义的集合和我们高中学习的集合基本是一样的,也就是具有无序性、确定性和唯一性。但在编程中也有有序的集合。

常用操作是求差集、补集、并集等等。

实现

常用语言的实现方式如下:

  • C:自己根据原理手写一个
  • C++:STL set (底层采用红黑树实现)
  • Java:set
  • Python:set

C++实现

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

int main(){
    set<int> s,s2;
    s.insert(10);
    s.insert(2);
    s.insert(3);
    for(auto it=s.begin();it!=s.end();it++)
        cout<<*it<<" ";
    cout<<endl;
    for(auto x:s)
        cout<<x<<" ";
    cout<<endl;
    // analyse the result, it is ordered. because set is finish by red-black tree(the tree is ordered)
    s2.insert(5);
    s2.insert(3);
    for(auto x:s2)
        cout<<x<<" ";
    cout<<endl;
    s.insert(s2.begin(),s2.end());
    for(auto x:s)
        cout<<x<<" ";
    cout<<endl;
    return 0;
}

//2 3 10
//2 3 10
//3 5
//2 3 5 10
//
//Process returned 0 (0x0)   execution time : 0.090 s
//Press any key to continue.

Python实现

Python直接使用set就行。

s=set()
s.add(1)
s.add(2)
print(s)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吉大秦少游

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值