C++ 的常見算法 之二

C++ 的常見算法 之二

  • 劃分序列
    • partition
    • stable_partition
  • 排序
    • sort
    • nth_element
  • 二分查找
    • binary_search

劃分序列

partition

重新排列 [first,last) 范圍內的元素,使得 pred 返回 true 的所有元素先于所有返回 false 的元素。迭代器返回指向第二組的第一個元素的點。

每個組內的相對順序不一定與調用之前相同。

#include <iostream>
#include <algorithm>
#include <vector>using namespace std;bool greater50 (int i) { return (i > 50); }
void print_val(int val) { cout << val << ' '; }
int main () {vector<int> myvector = {30, 40, 80, 12, 19, 20, 55, 72};vector<int>::iterator bound;bound = partition (myvector.begin(), myvector.end(), greater50);// print out content:cout << "greater than 50:";for (vector<int>::iterator it=myvector.begin(); it!=bound; ++it)cout << ' ' << *it;cout << '\n';cout << "less than 50:";for (vector<int>::iterator it=bound; it!=myvector.end(); ++it)cout << ' ' << *it;cout << '\n';for_each (myvector.begin(), myvector.end(), print_val);cout << endl;return 0;
}

結果屏幕輸出

greater than 50: 72 55 80
less than 50: 12 19 20 40 30
72 55 80 12 19 20 40 30

stable_partition

重新排列 [first,last) 范圍內的元素,pred 返回 true 的所有元素排在返回 false 的所有元素之前, 但與partition函數不同,這個函數保留每個組內元素的相對順序。

這通常使用內部臨時緩沖區來實現。

#include <iostream>
#include <algorithm>
#include <vector>using namespace std;bool greater30 (int i) { return (i > 30); }
void print_element(int val) { cout << val << " ";}int main () {vector<int> myvector = {4, 80, 5, 30, 6, 9, 50, 60, 1, 15};vector<int>::iterator bound;bound = stable_partition (myvector.begin(), myvector.end(), greater30);// print out content:cout << "greater than 30 elements:";for (vector<int>::iterator it=myvector.begin(); it!=bound; ++it)cout << ' ' << *it;cout << '\n';cout << "greater than or equal 30 elements: ";for (vector<int>::iterator it=bound; it!=myvector.end(); ++it)cout << ' ' << *it;cout << '\n';cout << "all elements: ";for_each (myvector.begin(), myvector.end(), print_element);cout << '\n';return 0;
}

結果屏幕輸出

greater than 30 elements: 80 50 60
greater than or equal 30 elements:  4 5 30 6 9 1 15
all elements: 80 50 60 4 5 30 6 9 1 15

排序

sort

將范圍 [first,last) 中的元素按升序排序。
第一個版本使用operator< 來比較元素,第二個版本使用comp 來比較元素。

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>using namespace std;struct personnel {string  name;int     age;
};bool myfunction (int i,int j) { return (i<j); }
void print_element(int val) { cout << val << " " ; }
void print_personnel(personnel person) { cout << person.name << " " << person.age << endl; }struct sort_class {bool operator() (personnel lf, personnel lr) { return (lf.age < lr.age);}
} sort_object;int main () {vector<int> myvector = {32,71,12,45,26,80,53,33}; vector<personnel> persons = {{"John", 30},{"Allison", 25},		  {"Sam", 29},		  {"Alice", 39},		  };// using default comparison (operator <):sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)// print out content:cout << "myvector contains:" << endl;for_each (myvector.begin(), myvector.end(), print_element);cout << '\n';// using object as compsort (persons.begin(), persons.end(), sort_object); // print out content:cout << "sorted personnel:" << endl;for_each (persons.begin(), persons.end(), print_personnel);cout << '\n';return 0;
}

結果屏幕·輸出

myvector contains:
12 32 45 71 26 33 53 80
sorted personnel:
Allison 25
Sam 29
John 30
Alice 39

nth_element

重新排序 [first,last) 范圍內的元素,得到的序列是,第 n 個位置的元素位置是,完全排序后,該元素所在的位置。

在結果序列中,其他元素沒有任何特定的順序,第 n 個元素前面的所有元素,都小于或對于該元素,它后面的元素都大于或等于它。

該算法有兩個版本,第一個版本使用operator< 來比較元素,第二個版本使用comp來比較元素。

#include <iostream>  
#include <algorithm> 
#include <vector> using namespace std;bool myfunction (int i,int j) { return (i<j); }
void print_element(int val)  { cout << val << " "; }struct personnel {string name;int  age;
};struct personnel_comp {bool operator()(personnel lf, personnel lr) {return (lf.age < lr.age);};
} person_comp;int main () {vector<int> myvector = {1, 9, 5, 8, 90, 30, 11};vector<int> v2 = {11, 19, 15, 18, 100, 40, 21, 130, 210};vector<personnel> v_persons = {{"John", 30},{"Allison", 25},		  {"Sam", 29},		  {"Alice", 39},};// using default comparison (operator <):nth_element (myvector.begin(), myvector.begin()+5, myvector.end());cout << "before sort:";for_each (myvector.begin(), myvector.end(), [](int val) ->void {cout << val << " ";});cout << endl;// using default compnth_element (myvector.begin(), myvector.begin()+5, myvector.end());// print out content:cout << " after sort:";for_each (myvector.begin(), myvector.end(),  [](int val) ->void {cout << val << " ";});cout << '\n';// using function as compcout << "before sort:" << endl;for_each (v2.begin(), v2.end(), [](int val) ->void {cout << val << " ";});cout << endl;nth_element (v2.begin(), v2.begin()+6, v2.end(), myfunction);cout << " after sort:";for_each (v2.begin(), v2.end(),  [](int val) ->void {cout << val << " ";});cout << '\n';// using function as compcout << "before sort:" << endl;for_each (v_persons.begin(), v_persons.end(), [](personnel p) ->void {cout << p.name << " " << p.age << endl;});cout << endl;nth_element (v_persons.begin(), v_persons.begin()+3, v_persons.end(), person_comp);cout << " after sort:" << endl;for_each (v_persons.begin(), v_persons.end(),  [](personnel p) ->void {cout << p.name << " " << p.age << endl;});cout << '\n';return 0;
}

程序運行結果屏幕輸出

before sort:9 1 5 8 11 30 90after sort:8 1 5 9 11 30 90
before sort:
11 19 15 18 100 40 21 130 210after sort:19 11 15 18 21 40 100 130 210
before sort:
John 30
Allison 25
Sam 29
Alice 39after sort:
Sam 29
Allison 25
John 30
Alice 39

二分查找

binary_search

如果范圍 [first,last) 中的任何元素值等于 val,則返回 true,否則返回 false。

該算法支持兩種版本。

  • 第一個版本,使用operator< 來比較元素,
  • 第二個版本,使用comp 來比較元素。如果 (!(a<b) && !(b<a)) 或 if (!comp(a,b) && !comp(b,a)),則 a 和 b 兩個元素被視為相同。

范圍中的元素應已根據相同的標準(operator< 或 comp)進行排序,或者至少根據 val 進行分區。

#include <iostream>
#include <algorithm>
#include <vector>using namespace std;bool myfunction (int i,int j) { return (i<j); }struct personnel {string name;int  age;
};struct personnel_comp {bool operator()(personnel lf, personnel lr) {return (lf.name < lr.name);};
} person_comp;int main () {std::vector<int> v = {1,2,40,30,3,4,5,20,10}; vector<personnel> v_persons = {{"John", 30},{"Allison", 25},		  {"Sam", 29},		  {"Alice", 39},};// using default comparison:sort (v.begin(), v.end());cout << " After sort: " << endl;for_each (v.begin(), v.end(), [](int v)->void{cout << v << " ";});cout << endl;cout << "looking for a 3... ";if (binary_search (v.begin(), v.end(), 3))cout << "found!\n"; else cout << "not found.\n";// using myfunction as comp:sort (v.begin(), v.end(), myfunction);cout << "looking for a 15... ";if (binary_search (v.begin(), v.end(), 15, myfunction))cout << "found!\n"; else cout << "not found.\n";// using personnel_comp as comp:cout << " Before sort: " << endl;for_each (v_persons.begin(), v_persons.end(), [](personnel v)->void{cout << v.name << " " << v.age << endl;});sort (v_persons.begin(), v_persons.end(), person_comp);cout << " After sort: " << endl;for_each (v_persons.begin(), v_persons.end(), [](personnel v)->void{cout << v.name << " " << v.age << endl;});cout << endl;cout << "looking for John... ";personnel person = {"John", 30}; if (binary_search (v_persons.begin(), v_persons.end(), person, person_comp))cout << "found!\n"; else cout << "not found.\n";return 0;
}

上述代碼運行后的屏幕輸出

 After sort:
1 2 3 4 5 10 20 30 40
looking for a 3... found!
looking for a 15... not found.Before sort:
John 30
Allison 25
Sam 29
Alice 39After sort:
Alice 39
Allison 25
John 30
Sam 29looking for John... found!

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

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

相關文章

Python開發——Python 線程入門

An Intro to Threading in Python – Real Python 1. 什么是線程&#xff1f; 線程是一個獨立的執行流程。這意味著您的程序將有兩件事情同時發生。但對于大多數 Python 3 實現來說&#xff0c;不同的線程實際上并不是同時執行的&#xff1a;它們只是看起來是這樣。 人…

Vue3中的jsx的babel配置

如果我們希望在項目中使用jsx&#xff0c;那么我們需要添加對jsx的支持&#xff1a; jsx我們通常會通過Babel來進行轉換&#xff08;React編寫的jsx就是通過babel轉換的&#xff09;&#xff1b;對于Vue來說&#xff0c;我們只需要在Babel中配置對應的插件即可&#xff1b; *…

Vue+Xterm.js+WebSocket+JSch實現Web Shell終端

一、需求 在系統中使用Web Shell連接集群的登錄節點 二、實現 前端使用Vue&#xff0c;WebSocket實現前后端通信&#xff0c;后端使用JSch ssh通訊包。 1. 前端核心代碼 <template><div class"shell-container"><div id"shell"/>&l…

C++ 實現字符串逆序

C 實現字符串逆序 思路&#xff1a; 輸入一個字符串。使用雙指針法&#xff0c;交換字符串的首尾字符&#xff0c;逐步向中間移動。輸出逆序后的字符串。 #include <iostream> #include <string>using namespace std;void reverseString(string &str) {int …

【FPGA】STA靜態時序分析

文章目錄 一.定義二.分類1. 靜態時序分析2. 靜態時序分析 三. 概念四. 時間余量1.場景2.建立時間余量3.保持時間余量 一.定義 時序分析:檢查電路是否滿足時序要求&#xff1b; 二.分類 1. 靜態時序分析 STA,遍歷所有的時序路徑&#xff0c;根據時序庫&#xff08;.lib文件&…

【Mojolicious RESTful接口全解】構建現代化Web服務的秘訣

標題&#xff1a;【Mojolicious RESTful接口全解】構建現代化Web服務的秘訣 Mojolicious是一個基于Perl的高性能、實時的Web框架&#xff0c;它以其簡潔的語法和強大的功能而聞名。Mojolicious不僅支持傳統的Web應用開發&#xff0c;還特別適合構建RESTful API。本文將詳細介紹…

新手教學系列——使用uWSGI對Flask應用提速

在構建和部署Flask應用時,性能和穩定性是兩個關鍵的因素。為了提升Flask應用的性能,我們可以借助uWSGI這個強大的工具。本文將詳細介紹為什么要使用uWSGI、uWSGI的底層原理,并提供一個實例配置,幫助你更好地理解和應用這個工具。 為什么要使用uWSGI uWSGI 是一個應用服務…

探索企業知識邊界,鴻翼ECM AI助手開啟智慧問答新時代

在信息化迅速發展的當下&#xff0c;企業積累的數字文檔數量巨大&#xff0c;這些文檔中蘊含的深層信息對業務發展至關重要。然而&#xff0c;傳統的搜索技術常常因只能進行關鍵字查詢而無法滿足對文檔深層次理解的需求。 據Gartner調查&#xff0c;高達47%的員工在尋找有效工…

Webpack: 三種Chunk產物的打包邏輯

概述 在前文 Webpack: Dependency Graph 管理模塊間依賴 中&#xff0c;我們已經詳細講解了「構建」階段如何從 Entry 開始逐步遞歸讀入、解析模塊內容&#xff0c;并最終構建出模塊依賴關系圖 —— ModuleGraph 對象。本文我們繼續往下&#xff0c;講解在接下來的「封裝」階段…

【大數據】—美國交通事故分析(2016 年 2 月至 2020 年 12 月)

引言 在當今快速發展的數字時代&#xff0c;大數據已成為我們理解世界、做出決策的重要工具。特別是在交通安全領域&#xff0c;大數據分析能夠揭示事故模式、識別風險因素&#xff0c;并幫助制定預防措施&#xff0c;從而挽救生命。本文將深入探討2016年2月至2020年12月期間&…

【redis】 LRU 和 LFU 算法

1、簡介 Redis 中的 LRU&#xff08;Least Recently Used&#xff09;和 LFU&#xff08;Least Frequently Used&#xff09;算法是用于決定在內存空間不足時&#xff0c;哪些鍵&#xff08;key&#xff09;應該被刪除以釋放空間的策略。這兩種算法都試圖通過跟蹤鍵的使用情況…

解決Memcached內存碎片:優化緩存性能的策略

解決Memcached內存碎片&#xff1a;優化緩存性能的策略 Memcached是一個廣泛使用的高性能分布式內存緩存系統&#xff0c;它通過在內存中緩存數據來加速數據檢索操作。然而&#xff0c;隨著時間的推移和緩存操作的進行&#xff0c;Memcached可能會遇到內存碎片問題&#xff0c…

24年河南特崗教師招聘流程+報名流程

河南特崗教師報名流程如下 1.登錄河南省特崗招聘網 登錄河南省特崗招聘網注冊賬號和密碼&#xff0c;賬號可以是手機號或者身份證號&#xff0c;密碼自己設置 2.注冊登錄賬號 注冊完賬號重新登錄賬號&#xff0c;輸入身份證號、手機號、密碼、驗證碼 3.瀏覽考試須知 填寫個人信…

Python 編程快速上手——讓繁瑣工作自動化(第2版)讀書筆記01 Python基礎快速過關

Python 編程快速上手——讓繁瑣工作自動化&#xff08;第2版&#xff09;讀書筆記01 Python基礎快速過關 1 python基礎概念 Python提供了高效的高級數據結構&#xff0c;還能簡單有效地面向對象編程。 python運算符順序 **——%——//——/——*——-——python中常見的數據…

Real-Time 3D Graphics with WebGL2

WebGL渲染管線 下圖是WebGL渲染管線的示意圖: Vertex Buffer Objects (VBOs) VBOS中包含了用于描述幾何體的信息。如&#xff0c;幾何體的頂點坐標&#xff0c;法線坐標&#xff0c;顏色&#xff0c;紋理坐標等。 Index Buffer Objects (IBOs) IBOs中包含了描述頂點關系的信…

C#的多線程UI窗體控件顯示方案 - 開源研究系列文章

上次編寫了《LUAgent服務器端工具》這個應用&#xff0c;然后里面需要新啟動一個線程去對文件進行上傳到FTP服務器&#xff0c;但是新線程里無法對應用主線程UI的內容進行更改&#xff0c;所以就需要在線程里設置主UI線程里控件信息的方法&#xff0c;于是就有了此博文。此文記…

Rocky Linux 9 快速安裝docker 教程

前述 CentOS 7系統將于2024年06月30日停止維護服務。CentOS官方不再提供CentOS 及后續版本&#xff0c;不再支持新的軟件和補丁更新。CentOS用戶現有業務隨時面臨宕機和安全風險&#xff0c;并無法確保及時恢復。由于 CentOS Stream 相對不穩定&#xff0c;剛好在尋找平替系統…

idm 支持斷點續傳嗎 idm 斷點續傳如何使用 idm斷點續傳怎么解決 idm下載中斷后無法繼續下載

斷點續傳功能&#xff0c;讓我再也不會懼怕下載大型文件。在斷點續傳的幫助下&#xff0c;用戶可以隨時暫停下載任務&#xff0c;并在空閑時繼續之前的下載進程。下載文件不懼網絡波動&#xff0c;斷點續傳讓下載過程更穩定。有關 idm 支持斷點續傳嗎&#xff0c;idm 斷點續傳如…

JavaScript:if-else類型

目錄 任務描述 相關知識 if語句 if-else語句 匹配問題 編程要求 任務描述 本關任務&#xff1a;根據成績判斷考試結果。 相關知識 在編程中&#xff0c;我們常常根據變量是否滿足某個條件來執行不同的語句。 JavaScript中利用以if關鍵字開頭的條件語句達到以上目的&am…