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

c++find函数用法

时间:2014-11-04 10:54:03      阅读:1992      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   sp   strong   文件   div   

头文件

#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函数用法

标签:style   blog   io   color   os   sp   strong   文件   div   

原文地址:http://www.cnblogs.com/kaituorensheng/p/4072901.html

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