关联式容器
关联式容器
1.set
构造set
1
2
3
4
5
6
7
8
9
10
using namespace set;
void test(){
set<int> nums;
set<int> nums2{1,2,3,4,5,2,3,4,6};
set<int> nums3 = nums2;
set<int> nums4(num2.begin(),num2.end());
}
遍历set
1
2
3
4
5
6
7
8
9
10
11
12
13
14 nums[0];//error
//set不支持下标访问,
//增强for循环
for(auto & ele:nums2){
cout << ele << endl;
}
//迭代器遍历
auto it = nums3.begin();
// it是这个类型 set<int>::iterator
for(:it != num3.end(); ++it){
cout << *it << endl;
}根据遍历可以发现set自动对元素进行升序排列,并且自带去重效果,只会保留一个
set查找操作
1
2
3
4
5
6
7
8
9
10
11
12 //一
cout << num2.count(2) << endl;
//返回结果只可能为1或者0,为1表示存在,为0表示不存在
//二
auto it2 = num2.find(1);
if(it2 == num2.end()){
cout << *it2 << endl;
}else{
cout << "NULL" << endl;
}
本文是转载或翻译文章,版权归原作者所有。转载本文请联系原作者。