21xrx.com
2025-03-27 00:25:50 Thursday
文章检索 我的文章 写文章
如何使用C++中的set?
2023-06-27 16:35:21 深夜i     15     0
C++ set 使用

Set是C++ STL中的一个关键字,表示无序的集合数据结构,在使用时需要包含头文件 。它的主要特点是元素不重复,并且可以自动排序。使用set比数组和向量要快,而且还可以在其中进行插入、删除、查找等操作。

1.创建set

通过set的构造函数可以创建一个set对象,代码如下:

#include <set>
using namespace std;
int main()
  set<int> s;
  return 0;

这段代码创建了一个空的int类型的set集合对象s,其中包含了无序的元素,由于元素按照升序排列,因此最小元素位于开头,最大元素位于结尾。

2.插入元素

使用insert()函数向集合中插入新的元素,代码如下:

#include <set>
using namespace std;
int main()
{
  set<int> s;
  s.insert(1);
  s.insert(2);
  s.insert(3);
  return 0;
}

以上代码通过insert()函数将1、2和3三个元素依次插入set集合中。

3.删除元素

使用erase()函数可以从set集合中删除指定的元素,代码如下:

#include <set>
using namespace std;
int main()
{
  set<int> s;
  s.insert(1);
  s.insert(2);
  s.insert(3);
  s.erase(2);
  return 0;
}

该代码将会删除set集合中的元素2,剩余的元素为1和3。

4.查找元素

使用find()函数可以查找set集合中是否存在指定的元素,代码如下:

#include <set>
using namespace std;
int main()
{
  set<int> s;
  s.insert(1);
  s.insert(2);
  s.insert(3);
  if (s.find(2) != s.end())
    cout << "元素2存在于集合中" << endl;
  return 0;
}

以上代码会在set集合中查找元素2,如果存在则输出“元素2存在于集合中”。

以上为使用C++中set的基本操作,它可以帮助程序员更方便的管理集合数据,提高程序运行效率。当然,除了基本操作以外,还有其他一些高级的操作可以使用,需要根据实际需求来使用。

  
  

评论区

请求出错了