2021-8-10 find函数

时间:2021-08-10
本文章向大家介绍2021-8-10 find函数,主要包括2021-8-10 find函数使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

C++ STL find函数总结

适用场景:

1. hash

stl的哈希map有专门的find&&count函数用来查找是否存在某个key
具体用法见用例

/*
* 哈希表的find返回的是一个迭代器,可以通过x->first访问Key,x->second访问val,如果找不到返回哈希表的end()位置
* 哈希表的count返回的是一个int类型的值,如果找到则返回1,找不到返回0
*/
{
    unordered_map<int,int> um;
    for(int i = 0;i<10;i++){
        um.insert({i,i+1});
    }
    unordered_map<int, int>::iterator x= um.find(3);
    int res= um.count(3);
    cout<<x->first<<endl;
    cout<<x->second<<endl;
    cout<<res<<endl;
    x=um.find(100);
    if(x==um.end()){
        cout<<"dont find! "<<endl;
    }
    system("pause");
    return 0;
}

stl其他容器也有find&&count方法,用法与哈希表相似
见下面用例:

{
    vector<int> arr;
    for(int i = 0; i < 100; i++){
        arr.push_back(i+3);
    }
    vector<int>::iterator x=find(arr.begin(),arr.end(),11);
    cout<<*x<<endl;             //11 , 输出的是值为11的迭代器,
    arr.push_back(10);
    int countname = count(arr.begin(),arr.end(),10);
    cout<<countname<<endl;      //2
    system("pause");
    }

除此之外string还有特殊的用法
见用例

{
    string str = "hello world";
    cout<<str.find("ll")<<endl;
    int a = str.find('s');
    cout<<a<<endl;   // -1
	//如果直接cout<<str.find('s')<<endl;输出的是一个非常大的数,没搞清楚为什么
	//但是做if判断的时候可行
	if(str.find('s')== -1){
        cout<<"dont find"<<endl;   //有效输出
    }
    return 0;
}

原文地址:https://www.cnblogs.com/jobshenlei/p/15123122.html