第3关:STL模板之关联容器:集合set的操作详解
2026/6/6 22:24:01 网站建设 项目流程

#include <iostream>

#include <cstring>

#include <algorithm>

#include <set>

using namespace std;

int main(int argc, const char * argv[]) {

/********* Begin *********/

// 1.创建空的int类型集合

set<int> st;

// 2.处理N次插入/删除操作

int N;

cin >> N;

for(int i=0; i<N; i++){

string op;

int x;

cin >> op >> x;

if(op == "insert"){

// 插入时:如果元素已存在,输出 "x in set"

if(st.find(x) != st.end()){

cout << x << " in set" << endl;

} else {

st.insert(x);

}

}

else if(op == "erase"){

// 删除时:如果元素不存在,输出 "x not in set"

if(st.find(x) == st.end()){

cout << x << " not in set" << endl;

} else {

st.erase(x);

}

}

}

// 3.遍历输出集合

cout << "print set: " << st.size() << endl;

if(!st.empty()){

for(set<int>::iterator it = st.begin(); it != st.end(); it++){

if(it != st.begin()) cout << " ";

cout << *it;

}

}

cout << endl;

// 4.处理M次查找操作

int M;

cin >> M;

for(int i=0; i<M; i++){

string op;

int x;

cin >> op >> x;

if(st.find(x) != st.end()){

cout << "find " << x << " in set" << endl;

}

else{

cout << "find " << x << " not in set" << endl;

}

}

// 5.清空集合

st.clear();

/********* End *********/

cout << st.size() << endl;

return 0;

}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询