c++set详解(C++set用法详解)

一、c set

c set类是c++ STL中的一个数据结构,它是一种关联容器,用于存储唯一且有序的元素。它可以采用红黑树、avl树等数据结构实现,其底层的实现与使用者无关。在c set容器中,元素是唯一的,从而可以防止容器中存储的元素出现重复。

c set类模板定义如下:

template<class T, class Compare = less,
class Allocator = allocator > class set;

T:表示set容器中的数据类型,可以是任何数据类型。

Compare:比较函数,也叫做比较对象,对于实现自定义数据类型的c set类,需要传递自定义的比较函数,否则,默认使用std::less函数进行默认排序。

Allocator:内存分配器,用于指定内存的存储位置,可以使用std::allocator类进行默认内存分配。

二、c set up o好噗四姑夫柚子

c set up是指从小到大的排序,而c set o是指从大到小的排序。默认情况下,c set采用从小到大的排序方式。如果用户需要使用从大到小的排序方式,需要通过自定义比较函数来实现。下面是一个从大到小排序的示例:

set<int, greater > mySet;
mySet.insert(1);
mySet.insert(3);
mySet.insert(2);
for (auto i : mySet)
   cout << i << " ";

输出结果为:3 2 1

三、c set 降序

c set容器是由于内部采用红黑树结构实现的,因此它的迭代器是一个双向迭代器,而不是随机访问迭代器。在使用迭代器进行遍历时,可以采取reverse_iterator的方式实现降序,而不需要使用sort等算法手动进行排序。下面是一个示例:

set mySet{ 1,2,3 };
for (auto it = mySet.crbegin(); it != mySet.crend(); it++)
   cout << *it << " ";

输出结果为:3 2 1

四、c set的实现

c set容器是一个基于红黑树实现的关联式容器,它与vector、deque等顺序式容器不同。在c set容器中,元素是唯一的,从而可以防止容器中存储的元素出现重复。红黑树是一种二叉查找树,它必须满足以下性质:

  • 每个节点都是红色或黑色
  • 根节点是黑色
  • 每个叶子节点(NULL节点)是黑色
  • 如果一个节点是红色的,则它的两个子节点都是黑色的
  • 从一个节点到该节点的所有叶子节点的路径上包含相同数目的黑色节点

红黑树的优点在于:

  • 查找和插入操作的时间复杂度O(logN)
  • 插入、删除元素时,保持set有序性
  • 支持自定义比较函数和默认排序

下面是一个c set的简单实现代码:

#include 
#include 
using namespace std;
int main()
{
    set mySet;
    mySet.insert(1);
    mySet.insert(2);
    mySet.insert(3);
    for (auto i : mySet)
        cout << i << " ";
    return 0;
}

五、c set用法

c set容器的用法与vector、deque等容器相似,通过insert和erase等函数来实现对容器中元素的增、删操作,支持随机访问、迭代器遍历等操作。下面是一些常用的c set用法示例:

1、查找元素

set mySet{ 1,2,3 };
if (mySet.find(2) != mySet.end())
    cout << "2 is found" << endl;

2、统计元素出现次数

set mySet{ 1,1,2,3 };
cout << "1 occurred " << mySet.count(1) << " times" << endl;

3、删除元素

set mySet{ 1,2,3,4 };
mySet.erase(2);
for (auto i : mySet)
    cout << i << " ";

输出结果为:1 3 4

六、c setw函数

c setw函数用于控制输出时所占的列数,通常用于表格型的输出。c++设置setw函数的方法如下:

cout << setw(5) << "1";
cout << setw(5) << "2";
cout << setw(5) << "3";

输出结果为:

    1    2    3

七、c set有序

c set容器有序,这意味着元素在插入时会根据元素的值进行排序,因此,c set中的元素是有序的。在c set中,可以通过自定义比较函数来控制元素的排序规则,从而实现多种排序方式。下面是一个根据字符串长度排序的示例:

struct StringLenComp
{
    bool operator()(const string &s1, const string &s2) const
    {
        return s1.size() < s2.size();
    }
};

set mySet{ "aaa", "bb", "ccccc" };
for (auto i : mySet)
    cout << i << " ";

输出结果为:bb aaa ccccc

八、c set的头文件

c set容器是c++ STL中的一种关联式容器,因此其头文件为set.h。但是,在c++标准库中,set容器的头文件为set,并且位于std命名空间之内,因此设置头文件如下:

#include 
using namespace std;

九、set up

set up是指从小到大的排序方式,在c set容器中,默认的排序方式即为set up。下面是一个示例代码:

set mySet;
mySet.insert(1);
mySet.insert(3);
mySet.insert(2);
for (auto i : mySet)
   cout << i << " ";

输出结果为:1 2 3

Published by

风君子

独自遨游何稽首 揭天掀地慰生平