C++ Primer 5th笔记(10)chapter10 泛型算法 : read
標準庫提供一組不依賴特定的容器類型的共性算法
- 指定迭代器范圍, eg. [begin, end)這種左閉包
- 3種類型: 只讀、寫、sort
1. find 查詢
template<class InIt, class T>
InIt find(InIt first, InIt last, const T& val);
查詢迭代器指定范圍[first, last)范圍內是否有val值。如果有,則返回該值對應的迭代器;否則,返回last表示查找失敗
eg. 結果為"42 a value -858993460"
int val = 42; vector<int> vec = {2, 42}; auto result = find(vec.cbegin(), vec.cend(), val); cout << " " << *result;string strVal = "a value"; list<string> lst = { "a value", "xxx", "yyy" }; auto result3 = find(lst.cbegin(), lst.cend(), strVal); cout << " " << *result3;int ia[] = { 32, 3 }; auto result2 = find(begin(ia), end(ia), val); cout << " " << *result2;2. accumulate 對范圍求和 (numeric.h)
template<class InIt, class T>
T accumulate(InIt first, InIt last, T val);
template<class InIt, class T, class Pred>
T accumulate(InIt first, InIt last, T val, Pred pr);
累加迭代器指定范圍[first, last)范圍內所有元素,再加上累加的初值val,返回累加的結果。第二個函數自定義操作:val = pr(val, *it)。
注:用于指定累加起始值的第三個參數是必要的,因為算法對將要累加的元素類型一無所知,沒有別的辦法創建合適的起始值或者關聯的類型。
eg. 結果為"6 a valuexxxyyy 45"
vector<int> vec1 = { 1,2,3 }; int result = accumulate(vec1.begin(), vec1.end(), 0); cout << " " << result;list<string> lst = { "a value", "xxx", "yyy" }; string result2 = accumulate(lst.cbegin(), lst.cend(), string("")); cout << " " << result2;std::array<int, 10> ia = { 1,2,3,4,5,6,7,8,9,0 }; auto result3 = accumulate(ia.cbegin(), ia.cend(), 0); cout << " " << result3;3. find_first_of算法
template<class FwdIt1, class FwdIt2>
FwdIt1 find_first_of(FwdIt1 first1, FwdIt1 last1, FwdIt2 first2, FwdIt2 last2);
template<class FwdIt1, class FwdIt2, class Pred>
FwdIt1 find_first_of(FwdIt1 first1, FwdIt1 last1, FwdIt2 first2, FwdIt2 last2, Pred pr);
查詢第一段范圍內與第二段范圍內任意元素匹配的元素的位置。如果找到,返回該元素對應的迭代器;否則,返回last1。第二個函數使用判斷:pr(*it1, *it2)來代替第一個函數中的判斷:*it1 == *it2。
eg. 輸出為"not found"
vector<int> vec = { 2, 42 };int ia[] = { 32, 3 };auto result = find_first_of(vec.cbegin(), vec.cend(), begin(ia), end(ia));if(result == vec.end())cout << "not found ";elsecout << " " << *result;4. equal
equal:判斷給定兩個區間是否相等。假定第二個序列至少與第一個序列一樣長 (algorithm.h)
eg.
并不要求兩個容器的元素類型相同,只要能使用比較運算符==就可以了。比如
eg. 輸出為"1"
5. count
查找個數
eg.輸出為2:
vector<int> v2 = { 4,5,6,7,8,9,4 }; auto result = count(v2.cbegin(), v2.cend(), 4);cout << " " << result;【引用】
總結
以上是生活随笔為你收集整理的C++ Primer 5th笔记(10)chapter10 泛型算法 : read的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue开发(2) 使用vue-cli来构
- 下一篇: C++ Primer 5th笔记(10)