在本章中,我们将学习:
1.设置介绍。
2.设置声明。
4.传递std :: set到函数
5.设置成员函数以遍历元素。
6.设置成员功能以检查容量。
7.设置成员函数来修改元素。
8.设置成员函数以执行元素操作。
1.设置介绍。
Set是存储唯一元素的容器。
这些元素以升序或降序存储。
集合中元素的值不能在容器中修改一次,它们始终是恒定的。
您只能插入或从容器中取出。
集通常实现为二进制搜索树。
在设置中,元素的值标识它(该值本身是T类型的键),
以下是用于设置的头文件:
#include <set>
2.设置声明。
set<int> myset = {5, 4, 3, 2, 1, 1, 2};
4.传递std :: set到函数
您可以通过2种方式传递集合:
1.传递价值
2.通过引用
1.传递价值
void func(set<int> myset) { myset.insert(30); } int main() { set<int> myset = {5, 4, 3, 2, 1, 1, 2}; func(myset); // as we are passing by value, the list will remain unchanged. std::cout << "myset contains:"<<endl; for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it) std::cout << ' ' << *it; return 0; }
2.通过引用
void func(set<int> &myset) { myset.insert(30); } int main() { set<int> myset = {5, 4, 3, 2, 1, 1, 2}; func(myset); // as we are passing by value, the list will remain unchanged. std::cout << "myset contains:"<<endl; for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it) std::cout << ' ' << *it; return 0; }
输出:
myset contains: 1 2 3 4 5 30
5.设置成员函数以遍历元素。
开始 :它将使迭代器返回到开始
结束 :它将返回迭代器结束
初学者 :它将返回反向迭代器返回到反向开始
撕裂 :它将反向迭代器返回到反向结束
开始 :它将const_iterator返回到开头
结束 :它将返回const_iterator结束
#include <iostream> #include <set> //for more tutorials 上 C, C ++, STL, DS visit www.ProDeveloperTutorial.com using namespace std; int main() { set<int> myset = {5, 4, 3, 2, 1, 1, 2}; std::cout << "myset contains using .begin():"<<endl; for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it) std::cout << ' ' << *it; std::set<int>::reverse_iterator rit; std::cout << "\nmyset contains using .rbegin:"<<endl; for (rit=myset.rbegin(); rit != myset.rend(); ++rit) std::cout << ' ' << *rit; std::cout << "\nmyset contains using .cbegin:"<<endl; for (auto it=myset.cbegin(); it != myset.cend(); ++it) std::cout << ' ' << *it; return 0; }
输出:
myset contains using .begin(): 1 2 3 4 5 myset contains using .rbegin: 5 4 3 2 1 myset contains using .cbegin: 1 2 3 4 5
6.设置成员功能以检查容量。
空的 :用于检查容器是否为空
尺寸 :用于返回容器大小
max_size :用于返回最大大小
7.设置成员函数来修改元素。
插入 :用于插入元素
抹去 :用于擦除元素
交换 :用于交换内容
明确 :用于清除内容
8.设置成员函数以执行元素操作。
找 :获取元素的迭代器
计数 :计算具有特定值的元素
lower_bound :将迭代器返回到下限
upper_bound :将迭代器返回上限