在c语言中find函数的使用方法,C ++ STL中的set :: find()函数

C ++ STL set::find()函数

set::find()函数是预定义的函数,用于检查元素是否属于集合,如果元素在集合容器中找到,则返回指向该元素的迭代器。

原型:set st; //声明

set::iterator it; //迭代器声明

it=st.find( const T item);

参数: const T项目

返回类型:迭代器位置

用法:

该功能检查元素是否属于集合。如果元素属于集合,则它返回确切的迭代器位置,否则返回st.end()。

示例For a set of integer,

set st;

set::iterator it;

st.insert(4);

st.insert(5);

set content:

4

5

it=st.find(5);

Print *it; //打印5-

it= st.find(7) //它= st.end()

包含的头文件:#include 

#include 

OR

#include 

C ++实现:#include 

using namespace std;

void printSet(set st){

set:: iterator it;

cout<

for(it=st.begin();it!=st.end();it++)

cout<

cout<

}

int main(){

cout<

set st;

set:: iterator it;

cout<

st.insert(4);

cout<

st.insert(6);

cout<

st.insert(10);

printSet(st); //打印当前设置

//查找元素6-

if(st.find(6)!=st.end())

cout<

else

cout<

//查找元素9-

if(st.find(9)!=st.end())

cout<

else

cout<

return 0;

}

输出结果Example of find function

inserting 4

inserting 6

inserting 10

Set contents are:

4 6 10

6 is present

9 is not present

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于你的问题,我可以为你提供一些帮助。 首先,让我们来看看如何使用C语言实现类似于STL的find函数。以下是一个简单的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> int find(int *arr, int size, int target) { for(int i = 0; i < size; i++) { if(arr[i] == target) { return i; } } return -1; } int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(int); int target = 4; int result = find(arr, size, target); printf("the index of %d is %d\n", target, result); return 0; } ``` 在这个例子,我们使用了一个简单的for循环来遍历整个数组,如果我们找到了目标元素,就返回它的索引。如果查找失败,我们返回-1。 接下来,让我们看看如何在C++使用find_if()函数。以下是一个示例代码: ```c++ #include <iostream> #include <vector> #include <algorithm> bool isOdd(int i) { return i % 2 == 1; } int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; auto it = std::find_if(vec.begin(), vec.end(), isOdd); if(it != vec.end()) { std::cout << "the first odd number is " << *it << std::endl; } else { std::cout << "no odd number is found" << std::endl; } return 0; } ``` 在这个例子,我们使用了一个名为isOdd()的函数来检查一个数字是否为奇数。我们使用std::find_if()函数来查找第一个奇数。如果找到了奇数,我们输出它的值。否则,我们输出一条消息表示没有找到奇数。 希望这些示例代码能够帮助你回答你的问题!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值