標籤:ons 演算法 分享 iter inpu auto 獨立 val alt
ITERATOR
template<class InputIterator,class T>
InputIterator find(InputIterator first,InputIterator last,const T& value)
{
while(first != last && *first != value)
++first;
return first;
}
程式碼範例
1 #include <iostream> 2 #include <vector> 3 #include <list> 4 #include <deque> 5 #include <algorithm> 6 #include <iostream> 7 8 using namespace std; 9 10 int main(int argc, char *argv[])11 {12 const int arraySize = 7;13 int ia[arraySize] = {0,1,2,3,4,5,6};14 15 vector<int> ivect(ia,ia+arraySize);16 list<int> ilist(ia,ia+arraySize);17 deque<int> ideque(ia,ia+arraySize);18 19 vector<int>::iterator it1 = find(ivect.begin(),ivect.end(),4);20 if(it1 == ivect.end())21 cout << "4 not found." << endl;22 else23 cout << "4 found. " << * it1 << endl;24 25 list<int>::iterator it2 = find(ilist.begin(),ilist.end(),6);26 if(it2 == ilist.end())27 cout << "6 not found. " << endl;28 else29 cout << "6 found. " << *it2 << endl;30 31 deque<int>::iterator it3 = find(ideque.begin(),ideque.end(),8);32 if(it3 == ideque.end())33 cout << "8 not found. " << endl;34 else35 cout << "8 find " << *it3 << endl;36 37 38 return 0;39 }
stl中容器有vector\set\list等等等等
演算法有find\count等
兩者獨立 而他們之間的聯絡便是由iterator進行串連 將兩者粘合起來
iterator類似智能指標
智能指標auto_ptr 除了擁有平常指標概念的功能 還具有引用計數功能
通過對該指標指向的元素的引用計數 自動釋放元素記憶體資源 而不必手動調用delete
範例程式碼如下
c++ stl源碼剖析學習筆記(二)iterator auto_ptr(老版本書籍樣本 新版本C++中已經廢除此概念)