STL源碼剖析 基本算法 equal | fill | iter_awap | lexicographical_compare | max | min | swap |mismatch

Equal

  • 兩個序列在[first,last)區間內相等,equal()返回true。以第一個序列作為基準,如果第二序列元素多不予考慮,如果要保證兩個序列完全相等需要比較元素的個數
if(vec1.size() == vec2.size() && equal(vec1.begin(),vec1.end(),vec2.begin()));
  • 或者可以使用容器提供的equality操作符,例如 vec1 == vec2
  • 如果第二序列比第一序列的元素少 ,算法內部進行迭代行為的時候,會超越序列的尾端,造成不可預測的結果
  • 第一版本缺省使用元素型別所提供的equality 操作符來進行大小的比較;第二版本使用指定的仿函數pred作為比較的依據?

template <class InputIterator1,class InputIterator2>
inline bool equal(InputIterator1 first1,InputIterator1 last1,InputIterator2 first2){//將序列一走過一遍,序列二亦步亦趨//如果序列一的元素多過序列二的元素個數 就會糟糕了while(first1 != first2){if(!(*first1 == *first2)){return false;}++first1;++first2;}//第二個版本
//    for (; first1 != last1;++first1,++first2){
//        if(*first1 != *first2){
//            return false;
//        }
//    }return true;
}//使用自定義的 仿函數pred作為比較的依據
template <class InputIterator1,class InputIterator2,class BinaryOperation>
inline bool equal(InputIterator1 first1,InputIterator1 last1,InputIterator2 first2,BinaryOperation binary_pred){while(first1 != first2){if(!binary_pred(*first1,*first2)){return false;}++first1;++first2;}return true;
}
#include <iostream>   //std::cout
#include <algorithm>  //std::equal
#include <vector>     //std::vectorbool my_predicate(int i,int j){return (i==j);
}int main(){int myints[] = {20,40,60,80,100};std::vector<int>my_vector(myints,myints+5);//using default comparison:if(std::equal(my_vector.begin(),my_vector.end(),myints)){std::cout << " equal! "<< std::endl;}else{std::cout << " differ! " << std::endl;}my_vector[3] = 94;if(std::equal(my_vector.begin(),my_vector.end(),myints, my_predicate)){std::cout << " equal! "<< std::endl;}else{std::cout << " differ! " << std::endl;}return 0;
}

fill

  • 將指定[first,last)內的所有元素使用新值填充
template<class ForwardIterator,class T>
void fill(ForwardIterator first,ForwardIterator last,const T& value){while (first!=last){*first = value;   //設定新值++first;          //迭代走過整個區間}
}
#include <iostream>   //std::cout
#include <algorithm>  //std::fill
#include <vector>     //std::vectorbool my_predicate(int i,int j){return (i==j);
}int main(){std::vector<int>my_vector(8); //0 0 0 0 0 0 0 0std::fill(my_vector.begin(),my_vector.begin()+4,5);std::fill(my_vector.begin()+3,my_vector.end()-2,8);std::cout << "my_vector contains:"<< std::endl;for(std::vector<int>::iterator it = my_vector.begin();it != my_vector.end();++it){std::cout << *it << " ";}return 0;
}

?fill_n

  • 將本地[first,last)內的前n個元素改寫為新的數值,返回迭代器指向被填入的最后一個元素的下一個位置
template<class OutputIterator,class Size,class T>
OutputIterator fill_n(OutputIterator first,Size n,const T&value){while (n>0){*first = value;--n;++first;}return first;
}
  • 如果n超過了容器的容量的上限,會造成什么樣的后果呢??
    int ia[3] = {0,1,2};std::vector<int>iv(ia,ia+3);std::fill_n(iv.begin(),5,7);
  • 迭代器進行的是assignment操作是一種覆寫操作,一旦超越了容器的大小會造成不可預期的結果。
  • 解決方法:使用insert產生一個具有插入性質而不是覆寫能力的迭代器。inserter()可以產生一個用來修飾迭代器的配接器,用法如下?
    int ia[3] = {0,1,2};std::vector<int>iv(ia,ia+3);
//    std::fill_n(iv.begin(),5,7);   //7 7 7std::fill_n(std::inserter(iv,iv.begin()),5,7); // 7 7 7 7 7 0 1 2 

iter_swap

  • ? ?

template <class ForwardIterator1, class ForwardIterator2>void iter_swap (ForwardIterator1 a, ForwardIterator2 b)
{swap (*a, *b);
}
// iter_swap example
#include <iostream>     // std::cout
#include <algorithm>    // std::iter_swap
#include <vector>       // std::vectorint main () {int myints[]={10,20,30,40,50 };              //   myints:  10  20  30  40  50std::vector<int> myvector (4,99);            // myvector:  99  99  99  99std::iter_swap(myints,myvector.begin());     //   myints: [99] 20  30  40  50// myvector: [10] 99  99  99std::iter_swap(myints+3,myvector.begin()+2); //   myints:  99  20  30 [99] 50// myvector:  10  99 [40] 99std::cout << "myvector contains:";for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)std::cout << ' ' << *it;std::cout << '\n';return 0;
}

?lexicographical_compare

  • 操作指針比較[first1 , last1) 和?[first2?, last2)對應位置上的元素大小的比較,持續到(1)某一組元素數據不相等;(2)二者完全相等,同時到達兩個隊列的末尾(3)到達last1或者last2
  • 要求第一序列按照字典排序方式而言不小于第二序列

  • lexicographical_compare - C++ Reference?
template<class InputIterator1,class InputIterator2>
bool lexicographical_compare(InputIterator1 first1,InputIterator1 last1,InputIterator2 first2,InputIterator2 last2){while (first1!=last1){if (first2 == last2 || *first2 < *first1){return false;} else if(*first1 < *first2){return true;}++first1;++first2;}return (first2 != last2);
}
// lexicographical_compare example
#include <iostream>     // std::cout, std::boolalpha
#include <algorithm>    // std::lexicographical_compare
#include <cctype>       // std::tolower// a case-insensitive comparison function:
bool mycomp (char c1, char c2)
{ return std::tolower(c1)<std::tolower(c2); }int main () {char foo[]="Apple";char bar[]="apartment";std::cout << std::boolalpha;std::cout << "Comparing foo and bar lexicographically (foo<bar):\n";std::cout << "Using default comparison (operator<): ";std::cout << std::lexicographical_compare(foo,foo+5,bar,bar+9);std::cout << '\n';std::cout << "Using mycomp as comparison object: ";std::cout << std::lexicographical_compare(foo,foo+5,bar,bar+9,mycomp);std::cout << '\n';return 0;
}

?max

  • 取兩個對象中的最大數值
  • 版本一使用greater-than操作符號進行大小的比較,版本二使用自定義comp函數比較
template <class T>
const T&max(const T&a,const T&b){return (a>b)?a:b;
}template <class T,class BinaryOperation>
const T&max(const T&a,const T&b,BinaryOperation binary_pred){return (binary_pred(a,b))?a:b;
}

min

  • 取兩個對象中的最小數值
  • 版本一使用less-than操作符號進行大小的比較,版本二使用自定義comp函數比較
template <class T>
const T&min(const T&a,const T&b){return (a<b)?a:b;
}template <class T,class BinaryOperation>
const T&min(const T&a,const T&b,BinaryOperation binary_pred){return (binary_pred(a,b))?a:b;
}

mismatch

  • 判斷兩個區間的第一個不匹配的點,返回一個由兩個迭代器組成的pair;pair的第一個迭代器指向的是第一區間第一個不匹配的點,第二個迭代器指向第二個區間的不匹配的點
  • 需要首先檢查迭代器是否不等于容器的end()?
  • 如果兩個序列的所有元素對應都匹配,返回的是兩個序列各自的last迭代器,缺省情況下使用equality操作符號來比較元素;第二版本允許用戶指定自己的比較操作
  • 需要第二個序列的元素個數要大于第一個序列,否則會發生不可預期的行為

template <class InputIterator1,class InputIterator2>
std::pair<InputIterator1,InputIterator2>mismatch(InputIterator1 first1,InputIterator1 last1,InputIterator2 first2){while ((first1!=last1)&&(*first1 == *first2)){++first1;++first2;}return std::make_pair(first1,first2);
}
  • 第二版本 pred(*first1,*first2)?

swap

  • 對調元素的內容
template <class T>
inline void swap(T&a,T&b){T tmp (a);a = b;b = tmp;
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/446222.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/446222.shtml
英文地址,請注明出處:http://en.pswp.cn/news/446222.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

svm分類器訓練詳細步驟_「五分鐘機器學習」向量支持機SVM——學霸中的戰斗機...

大家好&#xff0c;我是愛講故事的某某某。 歡迎來到今天的【五分鐘機器學習】專欄內容 --《向量支持機SVM》 今天的內容將詳細介紹SVM這個算法的訓練過程以及他的主要優缺點&#xff0c;還沒有看過的小伙伴歡迎去補番&#xff1a;【五分鐘機器學習】向量支持機SVM——學霸中的…

java一維數組的復制

題目 使用簡單數組(1)創建一個名為ArrayTest的類&#xff0c;在main()方法中聲明array1和array2兩個變量&#xff0c;他們是int[]類型的數組。(2)使用大括號{}&#xff0c;把array1初始化為8個素數&#xff1a;2,3,5,7,11,13,17,19。(3)顯示array1的內容。(4)賦值array2變量等…

STL源碼剖析 數值算法 copy 算法

copy復制操作&#xff0c;其操作通過使用assignment operator 。針對使用trivial assignment operator的元素型別可以直接使用內存直接復制行為(使用C函數 memove或者memcpy)節約時間。還可以通過函數重載(function overloading)、型別特性(type traits)、偏特化(partial speci…

python輸入數字成數組_python – Numpy:將數值插入數組的最快方法,使得數組按順序排列...

假設我有一個數組my_array和一個奇異值my_val. (請注意,my_array始終排序). my_array np.array([1, 2, 3, 4, 5]) my_val 1.5 因為my_val是1.5,我想把它放在1和2之間,給我數組[1,1.5,2,3,4,5]. 我的問題是&#xff1a;當my_array任意增大時,生成有序輸出數組的最快方式(即以微…

java 一維數組的反轉

代碼 public class ReverseArray {public static void main(String[] args) {String[] str {"AA", "BB", "CC", "DD"};System.out.println(Arrays.toString(str));reverse1(str);System.out.println(Arrays.toString(str));reverse2…

STL源碼剖析 數值算法 copy_backward 算法

copy_backward 時間技巧和copy類似主要是將[first&#xff0c;last)區間范圍內的元素按照逆行方向復制到以result-1為起點&#xff0c;方向同樣是逆行的區間上返回的迭代器的類型是result - (last - first)copy_backward支持的類型必須是BidirectionalIterators &#xff0c;才…

java線性查找和二分查找

線性查找 package lesson.l7_array;/*** Illustration** author DengQing* version 1.0* datetime 2022/6/23 14:19* function 線性查找*/ public class LineSearch {public static void main(String[] args) {String[]str{"AA","BB","CC"};boo…

python開發web項目_Django2:Web項目開發入門筆記(20)

該樓層疑似違規已被系統折疊 隱藏此樓查看此樓 這一篇教程&#xff0c;我們一起來了解如何在CentOS系統中將Django2的Web項目部署到Nginx服務器。 CentOS系統雖然和Ubuntu系統都是Linux系統&#xff0c;但是環境搭建和部署過程還是有一些區別。 整個流程分為幾個部分&#xff1…

STL源碼剖析 Set相關算法 并集 set_union|交集 set_intersection|差集 set_difference |對稱差集 set_symmetric_difference

注意事項 四種相關算法&#xff1a;并集、交集、差集、對稱差集本章的四個算法要求元素不可以重復并且經過了排序底層接受STL的set/multiset容器作為輸入空間不接受底層為hash_set和hash_multiset兩種容器 并集 set_union s1 U s2考慮到s1 和 s2中每個元素都不唯一&#xff0…

python sqlserver 數據操作_python對Excel數據進行讀寫操作

python對Excel數據進行讀寫操作將學習到的基礎操作記錄在這里&#xff0c;便與復習查看1.python讀取Excel工作簿、工作表import xlrd # 讀取工作簿 wbxlrd.open_workbook(招生表.xls) # 讀取工作簿下所有的工作表 wswb.sheets() # 讀取工作簿下所有工作表名稱 wsnamewb.sheet_n…

Arrays數組工具類

介紹 代碼 package lesson.l8_arrays;import java.util.Arrays;/*** Illustration** author DengQing* version 1.0* datetime 2022/6/23 16:53* function Arrays數組工具類*/ public class ArraysUtil {public static void main(String[] args) {int[] arr1 new int[]{1, 12…

通過解析URL實現通過Wifi的用戶查找

使用鏈接 遇見數據倉庫|遇見工具|IP地址精確查詢|WIFI精確查詢|在線語音識別|夢幻藏寶閣估價|福利資源|自定義導航-met.redhttps://sina.lt/ 操作步驟 打開第一個鏈接&#xff0c;點擊高精度IP定位&#xff0c;然后點擊右上角&#xff0c;創建一個Key&#xff0c;隨便輸入一…

anaconda中怎么sh_【好工具】 深度學習煉丹,你怎么能少了這款工具!JupyterLab 遠程訪問指南...

歡迎來到【好工具】專欄&#xff0c;本次我們給介紹一款可以進行遠程深度學習煉丹的工具 JupyterLab 及其配置流程&#xff0c;幫助讀者在本地進行調試&#xff0c;Max 開發效率。作者 & 編輯 | Leong導言不知道讀者們有沒有發現&#xff0c;如果你用 Anaconda 中的 Notebo…

java 類和對象 屬性和行為 成員變量和局部變量

概念 使用 案例 public class PersonText {public static void main(String[] args) {Person person new Person();person.name "dq";person.age 11;person.eat("番茄炒蛋");} }class Person {/*** 姓名*/String name;/*** 年齡*/Integer age;/*** 方…

STL源碼剖析 數值算法 heap算法

算法 adjacent_findcountcount_iffindfind_iffind_endfor_eachgenerategenerate_nincludesmax_elementmergemin_elementpartitionremoveremoveremove_copyremove_ifremove_copy_ifreplacereplace_copyreplace_ifreplace_copy_ifreversereverse_copyrotaterotate_copysearchsea…

java 學生對象數組

題目 代碼 package lesson.l10_oop;/*** Illustration** author DengQing* version 1.0* datetime 2022/7/1 9:57* function*/ public class Student {int number;int state;int score;public static final int NUM 20;public static void main(String[] args) { // 對…

STL源碼剖析 lower_bound | upper_bound | binary_search

lower_bound 二分查找的一種版本&#xff0c;試圖在已經排序的區間內查找元素value&#xff0c;如果區間內存在和value數值相等的元素&#xff0c;便返回一個迭代器&#xff0c;指向其中的第一個元素。如果沒有數值相等的元素&#xff0c;會返回假設這個元素存在的前提下應該出…

java能調用python嗎_如何使用運行時在Java中調用python程序 - java

我想用來自Java的參數調用python程序。但是我的輸出是空白。代碼在這里。 Python代碼在這里&#xff1a; import sys print(sys.argv[1]) Java代碼在這里&#xff1a; public class PrintNumber{ public static void main(String[] args){ Process proc; try { proc Runtime.g…

java 匿名對象

概念 代碼 package lesson.l10_oop;/*** Illustration** author DengQing* version 1.0* datetime 2022/7/1 13:39* function 匿名對象*/ public class Anonymous {public static void main(String[] args) { // 用法1new Teacher().say("dq");new Teacher()…

STL源碼剖析 第七章 仿函數(函數對象)

函數對象&#xff1a;具有函數性質的對象使得用戶像使用函數一樣使用它一般函數提供兩個版本&#xff0c;第一個版本使用operator < ;第二版本需要用戶 指定某種操作第二版本就是設計一個函數&#xff0c;將函數指針作為算法的一個參數&#xff1b;或者將函數操作設計成為一…