标准模板库(STL)使用说明 之 5 set

版权声明:请注明转发出处 https://blog.csdn.net/mafucun1988/article/details/89597384

STL(standard template library)是一个具有工业强度的高效C++程序库。它被容纳于C++标准程序库(C++ Standard Library)中,是ANSI/ISO C++标准中最新的也是极具革命性的一部分。该库包含了诸多在计算机科学领域里所常用的基本数据结构和基本算法。为广大C++程序员们提供了一个可扩展的应用框架,高度体现了软件的可复用性。
常见的容器主要有 vector,string,deque,pari,set,multiset,map,multimap 8种。
本文介绍:

  • 集合set
    • 初始化
    • set容器插入和删除
    • set容器查找
//初始化
set<int> myset; //默认构造
set<int> myset2(myset); //拷贝构造
//set容器插入和删除
set<int> myset; //默认从小到大排序
myset.insert(4);
myset.insert(2);
myset.insert(1);
myset.insert(5);
myset.insert(3);

myset.erase(myset.begin()); //删除第一个元素
myset.erase(2); //根据元素值删除
myset.erase(myset.begin(),myset.end()); // myset.clear()
int size = myset.size();
//插入函数对象
class mycompare04{
public:
    bool operator()(Teacher t1, Teacher t2){
        return t1.id > t2.id;
    }
};
set<Teacher, mycompare04> myset;
Teacher t1(1, 2), t2(3, 4), t3(5, 6);
myset.insert(t1);
myset.insert(t2);
myset.insert(t3);
for (set<Teacher, mycompare04>::iterator it = myset.begin(); it != myset.end();it ++){
    cout << it->id << " " << it->age << endl;
}
cout << endl;
set<Teacher, mycompare04>::iterator pos = myset.find(Teacher(3, 4));
if (pos == myset.end()){
    cout << "没有查找到!" << endl;
}
else{
cout << "查找到:" << pos->id << ":" << pos->age << endl;
}
//设置从大到小排序
template<class T>
class mycompare03{
public:
    bool operator()(T v1,T v2) const{
        return v1 > v2;
    }
};
set<int, mycompare03<int>> myset; 
myset.insert(4);
myset.insert(2);
myset.insert(1);
myset.insert(5);


//set容器查找
set<int>::iterator pos =  myset.find(20); //返回值为2的元素所在的位置
if (pos == myset.end()){
    cout << "没有查找到!" << endl;
}
else{
cout << "查找到:" << *pos << endl;
}
set<int> myset;
myset.insert(10);
myset.insert(5);
myset.insert(1);
myset.insert(8);

set<int>::iterator pos = myset.lower_bound(5);  //返回大于等于5 迭代器
if (pos == myset.end()){
    cout << "没有找到!" << endl;
}
else{
cout << "找到:" << *pos << endl;
}

pos = myset.upper_bound(5);//返回大于5 迭代器
if (pos == myset.end()){
    cout << "没有找到!" << endl;
}
else{
cout << "找到:" << *pos << endl;
}

pair<set<int>::iterator, set<int>::iterator> pos2 =  myset.equal_range(5);//返回大于等于5 迭代器 + 返回大于5 迭代器
if (pos2.first == myset.end()){
    cout << "meiyouzhaodao!" << endl;
}
else{
cout << "zhaodao!" << *(pos2.first) << endl;
}

if (pos2.second == myset.end()){
    cout << "meiyouzhaodao!" << endl;
}
else{
cout << "zhaodao!" << *(pos2.second) << endl;
}
  •  

猜你喜欢

转载自blog.csdn.net/mafucun1988/article/details/89597384