c++ find函數用法


轉:http://www.cnblogs.com/kaituorensheng/p/4072901.html (C++中find函數)

http://blog.csdn.net/huangyimin/article/details/6133650 (用於vector的find函數及STL的理解筆記)

find函數主要實現的是在容器內查找指定的元素,並且這個元素必須是基本數據類型的。查找成功返回一個指向指定元素的迭代器,查找失敗返回end迭代器。

注意:

  • find() 不屬於 vector 的成員,而存在於算法中,應加上頭文件 #include <algorithm>
  • string::find 這類型的函數,返回值類型都是 string::size_type (或者寫為 size_t 型), 而 string::size_type 其實是一種 unsigned int 類型。find 的結果記錄匹配的位置,或者返回一個名為 string::npos 的特殊值,說明查找沒有匹配。string 類將 npos 定義為保證大於任何有效下標的值。string::npos 的值是無符號型類型的,其值是(unsigned int)(-1),也就是4294967295

 

頭文件

#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;
}
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM