题解:P1059 [NOIP 2006 普及组] 明明的随机数

· · 题解

STL 好闪,拜谢 STL。

发现 STL 自带的 set 自带去重和排序的功能,于是直接利用 set 的特性即可 AC。

本题要用到的 set 语法:

另外,本题还需要迭代器来遍历 set,如果不了解详见此处。

话不多说,上代码。

#include <iostream>
#include <set>//记得引用set头文件
using namespace std;
int main() {
    set<int> st;//创建set
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        int x;
        cin >> x;
        st.insert(x);//将每一个元素插入set中,自动排序去重
    }
    cout<<st.size()<<endl;//输出set的大小(即去重和排序后剩余的个数)
    for (set<int>::iterator it = st.begin(); it != st.end(); it++)//使用迭代器遍历set
        cout << *it << " ";//输出每个数
    cout << endl;
    return 0;
}

求一键三连~