C++ find():泛型算法和成员函数

一、泛型算法:

泛型算法是STL库里面定义的一些算法,这些算法可以用一个接口操作各种数据类型,因此成为泛型算法。大多算法定义在头文件algorithm和numeric中。

find的前两个参数是表示元素范围的迭代器,第三个数是一个值,find将范围中的每个元素与给定的值进行比较,如果有匹配元素,则返回第一个等于给定值的元素的迭代器,如果无匹配值,则返回find中第二个用来表示范围的迭代器参数来表示搜索失败。

代码:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> v={1,2,3,4,5,6,7,8,9};
    vector<int>::iterator it;
    it=find(v.begin(),v.end(),9);
    if(it!=v.end())
        cout<<"find "<<*it<<endl;
    else
        cout<<"not find"<<endl;
    string s="zxcvbnm";
    string::iterator st;
    st=find(s.begin(),s.end(),'x');
    if(st==s.end())
        cout<<"not find"<<endl;
    else
        cout<<"find "<<*st<<endl;
    return 0;
}

输出:

二、成员函数

vector没有实现find函数,除此之外,常见容器都实现了自己的find函数。

String是这一种顺序存储结构,其find函数返回的是下标索引。

set,map,multiset,multimap都不是顺序索引的数据结构,所以返回的是迭代器。、

对于string,如果没有找到,则返回一个特殊标记string::nops,对于其它容器,返回end();

代码:

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main()
{
    string s="zxcvbnm";
    string::size_type n;
    n=s.find('x');
    if(n==s.npos)
        cout<<"not find"<<endl;
    else
        cout<<"find "<<n<<endl;
    map<string, int> m;
	m[string("abc")] = 1;
	m[string("defg")] = 2;
    map<string,int>::iterator it;
    it=m.find("abc");
    if(it!=m.end())
        cout<<it->first<<" "<<it->second<<endl;
    else
        cout<<"not find"<<endl;
    
    return 0;
}

输出:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值