C++ STL之集合set的使用

 

 set 的常用用法:

代码如下:

#include <iostream>
#include <set>
using namespace std;
int main()
{
	set<int> s; //定义一个空集合
	s.insert(1); //向集合s里面插入一个1
	cout << *(s.begin()) << endl; //输出集合s的第一个元素(前面的星号表示要对指针取值)
	
	for (int i = 0; i < 6; i++)
	{
		s.insert(i); // 向集合s里面插入i
	}
	
	for  (auto it = s.begin(); it != s.end(); it++) //用迭代器遍历集合s里面的每一个元素
	{
		cout << *it << " ";
	}
	
	cout << endl << (s.find(2) != s.end()) << endl; 
/*s.find(2)找二找到了会返回这个集合里面2所在的位置,里面是一个逻辑判断,会和后面s.end()这个位置判断,这两个位置不相等就返回一,它返回1,就意味着这个集合的最后一个元素不是2*/

	cout << (s.find(10) != s.end()) << endl;

	s.erase(1);// 删除集合s中的1这个元素
	cout << (s.find(1) != s.end()) << endl;
	return 0;
}

 

代码如下:

#include <bits/stdc++.h> 
using namespace std;
/*找到就返回第一次出现的串的第一个字符位置,找不到返回-1。*/ 
int main()
{
    string s;
    while(cin >> s)
    {
        int f = s.find("o");
        cout << f << endl;
    }
    return 0;
}

 

代码如下:

#include <iostream>
#include <set>
using namespace std;
int main()
{
     int a[] = {1,2,3};
     set<int> s(a,a+3);
     set<int>::iterator iter;
     if((iter = s.find(2)) != s.end())
     {
         cout<<*iter<<endl;
     }
     return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值