实现相关函数: #include <set> #include <iostream> #include "function.h" using namespace std; void insert(set<int>& s, int val); void erase(set<int>& s, int val); void erase(set<int>& s, set<int>::iterator& pos); set<int>::iterator find(set<int>& s, int val); // {val, val, val} void print(set<int>& s); int main() { set<int> s; for (int i = 0; i < 5; i++) { insert(s, i); } cout << "set size: " << s.size() << endl; print(s); auto it = find(s, 1); if (it != s.end()) { erase(s, it); } cout << "set size: " << s.size() << endl; print(s); if (s.count(2) == 1) { erase(s, 2); } cout << "set size: " << s.size() << endl; print(s); return 0; }输出:set size: 5 {0, 1, 2, 3, 4} set size: 4 {0, 2, 3, 4} set size: 3 {0, 3, 4}
时间: 2024-03-17 22:42:11 浏览: 17
实现如下:
```cpp
void insert(set<int>& s, int val) {
s.insert(val);
}
void erase(set<int>& s, int val) {
s.erase(val);
}
void erase(set<int>& s, set<int>::iterator& pos) {
s.erase(pos);
}
set<int>::iterator find(set<int>& s, int val) {
return s.find(val);
}
void print(set<int>& s) {
cout << "{";
for (auto it = s.begin(); it != s.end(); it++) {
cout << *it;
if (next(it) != s.end()) {
cout << ", ";
}
}
cout << "}\n";
}
```
输出结果:
```
set size: 5
{0, 1, 2, 3, 4}
set size: 4
{0, 2, 3, 4}
set size: 3
{0, 3, 4}
```
相关问题
请帮我逐句解释下列代码: #include<stdio.h> //f(n)=g(n)+h(n) #include<iostream> #include<cstring> #include<queue> #include<set> using namespace std;
这段代码是一个C++程序,包含了一些头文件的引用和命名空间的声明。下面是对代码的逐句解释:
1. `#include<stdio.h>`:引用了C标准库中的stdio.h头文件,该头文件包含了一些输入输出函数的声明,比如printf和scanf等。
2. `#include<iostream>`:引用了C++标准库中的iostream头文件,该头文件包含了一些输入输出流对象的声明,比如cin和cout等。
3. `#include<cstring>`:引用了C++标准库中的cstring头文件,该头文件包含了一些字符串处理函数的声明,比如strlen和strcpy等。
4. `#include<queue>`:引用了C++标准库中的queue头文件,该头文件包含了队列容器的声明和相关操作函数的定义。
5. `#include<set>`:引用了C++标准库中的set头文件,该头文件包含了集合容器的声明和相关操作函数的定义。
6. `using namespace std;`:使用了std命名空间,这样就可以直接使用std命名空间下的函数和对象,而不需要加上命名空间前缀。
总结起来,这段代码主要是引用了一些标准库的头文件,并使用了std命名空间。
#include <iostream> #include<algorithm> #include<cmath> #include <queue> using namespace std;
#include <iostream>:这是C++标准库中的头文件,用于输入输出流操作,包括cin、cout等。
#include<algorithm>:这是C++标准库中的头文件,用于提供各种算法操作,如排序、查找等。
#include<cmath>:这是C++标准库中的头文件,用于提供数学函数操作,如绝对值、平方根等。
#include <queue>:这是C++标准库中的头文件,用于提供队列操作,包括入队、出队等。
using namespace std;:这是C++的命名空间声明,表示使用std命名空间,可以直接使用std中的函数和对象。