您的位置:首页 > 编程语言 > C语言/C++

C++ find 函数用法

2015-06-17 15:40 405 查看

头文件

#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(m.begin(), m.end(), "hello") == m.end())
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;
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;
}


注意:

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

#include <iostream>
#include <algorithm>
#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;
}


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

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

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

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


转载自 jihite
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: