一、stlfind指南
stlfind是STL庫中的一個函數,主要用於遍歷容器中的元素並找到符合條件的元素。stlfind是在頭文件algorithm中定義的,其函數原型如下:
template InputIterator find(InputIterator first, InputIterator last, const T& value);
其中,first和last是表示所要查找元素範圍的迭代器(容器中的首元素和尾元素對應的迭代器),value是要查找的元素的值或者類型。
使用stlfind函數時,需要注意以下幾點:
1、stlfind函數返回查找到的元素的迭代器。如果沒有找到符合條件的元素,則返回last迭代器。
2、stlfind函數只能查找第一次出現符合條件的元素,不能查找多個。
3、如果查找的容器是一個無序容器(如set、map等),則查找操作時間複雜度為O(logn),如果是有序容器(如vector、deque等),則查找操作時間複雜度為O(n)。
二、stlfindserch函數
stlfindserch函數是stlfind函數的加強版,其函數原型如下:
template ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2);
其中,first1和last1表示要查找的範圍,first2和last2表示要查找的子序列範圍。
stlfindserch函數用於查找一個序列在另一個序列中第一次出現的位置,如下面的示例代碼:
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector v1 = {1,2,3,4,5}; vector v2 = {3,4}; auto it = search(v1.begin(), v1.end(), v2.begin(), v2.end()); if(it != v1.end()) cout << "find at " << it - v1.begin() << endl; else cout << "not find" << endl; return 0; }
上述代碼中,stlfindserch函數將在v1中查找v2序列第一次出現的位置。在本例中,v2序列在v1中第一次出現的位置是2,因此函數返回值是v1.begin()+2。
三、stlfind函數實例
下面通過實例來進一步了解stlfind函數。
1、在vector容器中查找指定元素的位置:
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector v = {1,2,3,4,5,6,7,8,9,10}; int x = 5; auto it = find(v.begin(), v.end(), x); if(it != v.end()) cout << "find at " << it - v.begin() << endl; else cout << "not find" << endl; return 0; }
上述代碼中,使用stlfind函數查找容器v中是否含有元素x,如果有,則輸出x在容器中的位置。
2、在list容器中查找自定義類型的元素:
#include <iostream> #include <algorithm> #include <list> using namespace std; class Student { public: int num; string name; bool operator==(const Student &s) { return this->num == s.num; } }; int main() { list ls; Student s1 = {1, "張三"}; Student s2 = {2, "李四"}; Student s3 = {3, "王五"}; ls.push_back(s1); ls.push_back(s2); ls.push_back(s3); Student s4 = {2, "李四"}; auto it = find(ls.begin(), ls.end(), s4); if(it != ls.end()) cout << "find " <name << endl; else cout << "not find" << endl; return 0; }
上述代碼中,使用stlfind函數在list容器中查找Student類對象s4的位置,如果找到,則輸出對應的學生姓名。
四、結語
stlfind函數是STL庫中非常常用的函數,用於在容器中查找指定元素。在實際編程中,需要根據具體的情況選擇不同的查找方式,以達到最優效果。
原創文章,作者:QCNPN,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/330191.html