c++find函数用法

时间:2025-01-29 15:27:41

c++find函数用法

头文件

#include <algorithm>

函数实现

复制代码

template<class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val)
{
  while (first!=last) 
  {
     if (*first==val) return first;
     ++first;
   }
    return last;
}

复制代码
例1(vector)

复制代码

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

int main()
{
    vector<string> m;
    m.push_back("hello");
    m.push_back("hello2");
    m.push_back("hello3");
    if (find((), (), "hello") == ())
        cout << "no" << endl;
    else
        cout << "yes" << endl;
}

复制代码
例2(set)

复制代码

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

int main()
{
    set<string> m;
    ("hello");
    ("hello2");
    ("hello3");
    if (find((), (), "hello") == ())
        cout << "no" << endl;
    else
        cout << "yes" << endl;
}

复制代码

注1:set自身有个find函数,举例如下:

复制代码

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

int main()
{
    set<string> m;
    ("hello");
    ("hello2");
    ("hello3");
    if (find((), (), "hello") == ())
        cout << "no" << endl;
    else
        cout << "yes" << endl;
}

复制代码
注2:string自身有个find函数,举例如下:

复制代码

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

int main()
{
    string s = "helllo";
    if (("e") == string::npos)  //yes
        cout << "no" << endl;
    else
        cout << "yes" << endl;

    if (("z") == string::npos)  //no
        cout << "no" << endl;
    else
        cout << "yes" << endl;
}