码迷,mamicode.com
首页 > 编程语言 > 详细

c++中find函数的用法

时间:2015-03-14 18:10:43      阅读:305      评论:0      收藏:0      [点我收藏+]

标签:

find函数主要实现的是在容器内查找指定的元素,并且这个元素必须是基本数据类型的。
查找成功返回一个指向指定元素的迭代器,查找失败返回end迭代器。

头文件

#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;
}

c++中find函数的用法

标签:

原文地址:http://www.cnblogs.com/yaoyueduzhen/p/4337791.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!