须知:在尖括号中定义你容器里的元素类型 set<int> name
使用前提,#include<set>
特征:
set集合存储唯一元素,
1.按升序自动排序。
2.是唯一的,也就是说set里相同的值会被忽略。
eg:
#include <iostream>
#include <set>
using namespace std;
int main() {
// Create a set with two equal elements (BMW is listed two times)
set<string> cars = {"Volvo", "BMW", "Ford", "BMW", "Mazda"};
// Print set elements
for (string car : cars) {
cout << car << "\n";
}
return 0;
}
运行结果:
3.可以添加或删除,但是不能修改当前有的元素的值。
4.内部排序
不能按索引号访问,set内部是将你赋值后的set排序过的,不再是赋值时的顺序。
eg:
#include<iostream>
#include<set>
int main()
{
std::set<std::string> cars = {"Volvo","BMW","Ford","Mazda"};
for(std::string car: cars){
std::cout<<car<<std::endl;
}
std::cin.get();
}
运行结果:
可以看到它是按照字母表的顺序进行排序的
整型eg:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> numbers = {1, 7, 3, 2, 5, 9};
for (int num : numbers) {
cout << num << "\n";
}
return 0;
}
运行结果:
由此可知整型是从小到大的排序的。
内部翻转顺序
所以,在默认情况下,集中的元素按升序排序。如果我们需要翻转顺序,可以通过在尖括号里用greater<type>,在声明时使用
eg:
#include <iostream>
#include <set>
using namespace std;
int main() {
// Create a set called numbers that will store integers
set<int, greater<int>> numbers = {1, 7, 3, 2, 5, 9};
// Print set elements
for (int num : numbers) {
cout << num << "\n";
}
return 0;
}
运行结果:
添加元素
用.insert(),添加进去后的值也会被自动排序
eg:
#include <iostream>
#include <set>
using namespace std;
int main() {
// Create a set called cars that will store strings
set<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
// Add new elements
cars.insert("Tesla");
cars.insert("VW");
cars.insert("Toyota");
cars.insert("Audi");
// Print set elements
for (string car : cars) {
cout << car << "\n";
}
return 0;
}
运行结果:
删除元素
用.erase(),括号内为要删除的元素,若要删除所有元素用.clear()
查看大小函数:
.size()
检测是否为空
.empty()
count(val)函数
它在容器中搜索与 val 等效的元素并返回匹配的数量。
#include <iostream>
#include <set>
using namespace std;
int main () {
set<int> myset;
for (int i = 1; i < 15;++i) myset.insert(i*5);
for (int i = 0; i < 5; ++i) {
std::cout << i;
if (myset.count(i)!=0)
std::cout << " is an element of myset.\n";
else
std::cout << " is not an element of myset.\n";
}
return 0;
}
运行结果:
find(val)函数
它在容器中搜索等效于 val 的元素,如果找到则返回一个迭代器,否则返回一个迭代器到 set::end。
#include <iostream>
#include <set>
using namespace std;
int main () {
set<int> myset;
set<int>::iterator it;
for (int i = 1; i <= 10; i++) myset.insert(i*10);
it = myset.find(40);
myset.erase (it);
myset.erase (myset.find(60));
std::cout << "myset contains:";
for (it = myset.begin(); it!=myset.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}
运行结果:
unordered_set
它是一个关联容器,以无特定顺序存储唯一元素,并允许根据其值快速检索单个元素。