c++ find 函数用法

头文件

1

函数实现

1
2
3
4
5
6
7
8
9
10
template<class , class T>
find ( first, last, const T& val)
{
while (first!=last)
{
if (*first==val) return first;
++first;
}
return last;
}

举例

  1. vector
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    #include <iostream>

    #include <vector>
    using namespace std;

    int main()
    {
    vector<string> m;
    m.push_back("hello");
    m.push_back("hello2");
    m.push_back("hello3");
    if (find(m.begin(), m.end(), "hello") == m.end())
    cout << "no" << endl;
    else
    cout << "yes" << endl;
    }
  2. set
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    #include <iostream>

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

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

注意:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

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

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

string自身有个find函数,举例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

#include <string>
using namespace std;

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

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