c++11之all_of 、 any_of 和 none_of 的用法


0.時刻提醒自己

Note: vector的釋放

1.區別

函數 功能
all_of 區間[開始, 結束)中是否所有的元素都滿足判斷式p,所有的元素都滿足條件返回true,否則返回false。
any_of 區間[開始, 結束)中是否至少有一個元素都滿足判斷式p,只要有一個元素滿足條件就返回true,否則返回true。
none_of 區間[開始, 結束)中是否所有的元素都不滿足判斷式p,所有的元素都不滿足條件返回true,否則返回false。

all_of 與 none_of 是相反的,這樣就不用修改判斷條件了,換函數就行。

2.all_of用法

2.1 代碼

// 分數
std::vector<int> vec_score{10 , 2, 33, 43, 52};

// 是否大於100
bool is_greater_than_100 = std::all_of(vec_score.begin(), vec_score.end(), [](int &item) {return 100 < item; });

if (!is_greater_than_100)
	std::cout << "不全大於100\n\n";
else
	std::cout << "全大於100\n\n";

2.2 輸出結果

3.any_of用法

3.1 代碼

// 分數
std::vector<int> vec_score{10 , 2, 33, 43, 52};

// 是否存在大於100的元素
bool is_exist_greater_than_100 = std::any_of(vec_score.begin(), vec_score.end(), [](int &item) {return 100 < item; });

if (is_exist_greater_than_100)
	std::cout << "存在大於100的分數\n";
else
	std::cout << "不存在大於100的分數\n\n";

3.2 輸出結果

4.none_of 用法

4.1 代碼

// 分數
std::vector<int> vec_score{10 , 2, 33, 43, 52};

// 檢查所有分數是否全部不大於100
bool is_less_than_100 = std::none_of(vec_score.begin(), vec_score.end(), [](int &item) {return 100 < item; });

if (is_less_than_100)
	std::cout << "所有分數都不大於100\n";
else
	std::cout << "存在大於100的分數\n\n";

4.2 輸出結果

5.異常

其實,上面的代碼寫的不夠規范,因為這三個函數可能會拋出異常。 參考cppreference

擁有名為 ExecutionPolicy 的模板形參的重載按下列方式報告錯誤:
◦若作為算法一部分調用的函數的執行拋出異常,且 ExecutionPolicy 為標准策略之一,則調用 std::terminate 。對於任何其他 ExecutionPolicy ,行為是實現定義的。
◦若算法無法分配內存,則拋出 std::bad_alloc 。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM