题解:STL set

· · 题解

:::info[题意简述]

原题链接。

给定一些数字,输出去重并排序之后的结果。

:::

思路

注意到 C++ 中有个东西叫做 STL,又注意到 STL 中有个东西叫做 set。set 的一些常用操作如下:

set 作为集合,有两个特性:

以上两个特性刚好符合题目描述,因此可以直接把输入的元素储存到 set 中,然后再遍历 set 中的元素依次输出即可。

代码

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n;
set<ll> a;
void solve()
{
    cin >> n;
    while (n--)
    {
        int x;
        cin >> x;
        a.insert(x);
    }
    cout << a.size() << endl;
    for (int v : a) // 遍历 a 中的每一个元素
    {
        cout << v << ' ';
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    ll t = 1;
    // cin >> t;
    while (t--)
    {
        solve();
    }
    return 0;
}