set 是 C++ 标准模板库(STL)中提供的有序关联容器之一。基于红黑树(Red-Black Tree)实现,用于存储一组唯一的元素,并按照元素的值进行排序。
常见问题
1、如何检查 std::set 中是否存在某个值?
- 使用
find
,知道,返回值的迭代器,否则返回end()
if (mySet.find(key) != mySet.end()){函数体}
可以用来遍历2、set的迭代器是什么类型
双向迭代器
。不能随机访问,可以向把迭代器进行后-- 或向前++。3、set的迭代器失效?
- set主要
与删除有关
,被删除的元素的迭代器会失效。但是,由于红黑树的性质,删除操作不会影响到其他元素的迭代器,所以除了被删除元素的迭代器外,其他迭代器仍然有效。
#include
setname
setname
std::set<int> s1; // 默认升序:{1, 2, 3}
std::set<int, std::greater<int>> s2; // 降序:{3, 2, 1}
struct Person {
std::string name;
int age;
};
// 定义比较仿函数(按年龄升序)
struct CompareAge {
bool operator()(const Person& a, const Person& b) const {
return a.age < b.age;
}
};
std::set<Person, CompareAge> peopleSet;
peopleSet.insert({"Alice", 25});
peopleSet.insert({"Bob", 30});
#include
#include
using namespace std;
int main(){
set<int>set1={1,2,3,4};
set1.insert(3);
for(auto i: set1){
cout<<i<<" "<<endl;
}
/*
1
2
3
4
*/
}
int main(){
set<int>set1={1,2,3,4};
set<int>set2={7,6,5};
set1.insert(set2.begin(),set2.end());
for(auto i: set1){
cout<<i<<" ";
}
/*
1 2 3 4 5 6 7
*/
}
int main(){
set<int>set1={1,2,3,4};
set<int>set2={7,6,5};
set1.insert(set1.begin(),2);
for(auto i: set1){
cout<<i<<" ";
}
/*
1 2 3 4
*/
}
int main(){
set<int>set1={1,2,3,4};
set1.erase(set1.begin());
for(auto i: set1){
cout<<i<<" ";
}
/*
2 3 4
*/
}
int main(){
set<int>set1={1,2,3,4};
set1.erase(2);
for(auto i: set1){
cout<<i<<" ";
}
/*
1 3 4
*/
}
int main(){
set<int>set1={1,2,3,4};
set1.erase(set1.begin(),++set1.begin());
for(auto i: set1){
cout<<i<<" ";
}
/*
2 3 4
*/
}
int main(){
set<int>set1={1,2,3,4};
auto i =set1.begin();
set<int>::iterator it=set1.end();
cout<<*i<<endl;//1
cout<<*it<<endl;//4
}
int main(){
set<int>set1={1,2,3,4};
set<int>set2={3,4};
set1.swap(set2);
for(auto i: set1){
cout<<i<<" ";//3 4
}
}
int main(){
set<int>set1={1,2,3,4};
auto i =set1.count(1);
cout<<i<<endl;//1
}
int main(){
set<int>set1={1,2,3,4};
auto i =set1.find(1);
cout<<*i<<endl;//1
}
int main(){
set<int>set1={1,2,3,4};
auto i =set1.size();
cout<<i<<endl;//4
}
int main(){
set<int>set1={1,2,3,4};
if(set1.empty()==0){
cout<<"set1有元素"<<endl;//set1有元素
}else{
cout<<"无元素"<<endl;
}
}
int main(){
set<int>set1={1,2,3,4};
set1.clear();
for(auto i: set1){
cout<<i<<" ";
}
}
int main(){
set<int>set1={1,2,3,4};
auto i = set1.lower_bound(2);
cout<<*i<<endl;//2
}
int main(){
set<int>set1={1,2,3,4};
auto i = set1.upper_bound(2);
cout<<*i<<endl;//3
}