set相關容器

2021-10-17 09:13:23 字數 2388 閱讀 1596

簡介:

本質:

set和multiset區別

功能描述:建立set容器以及賦值

構造:

賦值:

示例:

#include //構造和賦值

sets1;

s1.insert(10);

s1.insert(30);

//拷貝構造

sets2(s1);

//賦值

sets3;

s3 = s2;

函式原型:

示例:

#include sets1;

s1.insert(10);

s1.insert(30);

if (s1.empty())

else

//交換

sets1;

s1.insert(10);

sets2;

s2.insert(100);

s1.swap(s2);

函式原型:

示例:

#include //插入和刪除

sets1;

//插入

s1.insert(10);

//刪除

s1.erase(s1.begin());

s1.erase(30);

//清空

s1.end());

s1.clear();

函式原型:

示例:

#include sets1;

//插入

s1.insert(10);

s1.insert(30);

//查詢

set::iterator pos = s1.find(30);

if (pos != s1.end())

else

//統計

int num = s1.count(30);

cout << "num = " << num << endl;

注意:

區別:

兩種建立方式:

示例:

#include //對組建立

pairp(string("tom"), 20);

cout << "姓名: " << p.first << " 年齡: " << p.second << endl;

pairp2 = make_pair("jerry", 10);

利用仿函式,可以改變排序規則

示例一set存放內建資料型別

#include class mycompare 

};void test01()

cout << endl;

//指定排序規則

sets2;

s2.insert(10);

s2.insert(40);

for (set::iterator it = s2.begin(); it != s2.end(); it++)

cout << endl;

}

示例二set存放自定義資料型別

#include #include class person

string m_name;

int m_age;

};class compareperson

};void test01()

}

同樣的,一看見unordered就可以猜測到底層和set不同,體現了無序特性。

1.利用set集合不允許插入重複元素的特性,我們可以統計非重複出現元素的個數

unordered_set<

int> fathers;

int ret;

fathers.

insert(1

);fathers.

insert(1

);fathers.

insert(2

);fathers.

insert(3

);ret = fathers.

size()

;//結果應該為3

set容器 map容器

簡介 本質 set和multiset區別 構造 賦值 include void printset set int s cout endl 構造和賦值 void test01 intmain 總結 函式原型 include void printset set int s cout endl 大小 vo...

set容器總結

1.關於set c stl 之所以得到廣泛的讚譽,也被很多人使用,不只是提供了像vector,string,list等方便的容器,更重要的是stl封裝了許多複雜的資料結構演算法和大量常用資料結構操作。vector封裝陣列,list封裝了鍊錶,map和set封裝了二叉樹等,在封裝這些資料結構的時候,s...

set 集合容器

簡單學習一下set集合容器 標頭檔案 include using namespace std sets 必須是有定義 運算子的型別 int,string 向s中加資料 s.insert elem 插入elem之後元素預設按公升序排序,集合中是沒有重複元素的,每個不同的元素只存乙個 s.clear 清...