c++find関数の使い方

9155 ワード

ヘッダファイル
#include
関数の実装
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;
}