C++ STL庫應用匯總
1、std::max_element的使用
std::min_element類似,求最小
#include <iostream>
#include <iterator>
#include <QApplication>
bool myfn( int i, int j )
{
return i < j;
}
int main( int argc, char* argv[] )
{
QApplication a( argc, argv );
std::list<int> zx {1, 2, 3, 8, 5, 44};
//方法一 調用函數
auto biggest = std::max_element( std::begin( zx ), std::end( zx ), myfn );
std::cout << "Max element is " << *biggest
<< " at position " << std::distance( std::begin( zx ), biggest ) << std::endl;
//方法二 調用Lamda表達式
auto nn = std::max_element( std::begin( zx ), std::end( zx ), []( int& i, int& j ) -> bool
{
return i < j;
} );
std::cout << "Max element is " << *nn
<< " at position " << std::distance( std::begin( zx ), biggest ) << std::endl;
return a.exec();
}
升級可以用到任務隊列管理中,通過任務優(yōu)先級,選擇優(yōu)先級最高的任務
auto max_pos =
std::max_element( m_taskList.cbegin(), m_taskList.cend(),
[]( const TaskManagePtr & task1, const TaskManagePtr & task2 ) -> bool
{
return task1->priority() < task2->priority();
} );
知識點擴展:
C++ 的標準模板庫(Standard Template Library,STL)是泛型程序設計最成功應用的實例。STL 是一些常用數據結構(如鏈表、可變長數組、排序二叉樹)和算法(如排序、查找)的模板的集合,主要由 Alex Stepanov 主持開發(fā),于 1998 年被加入 C++ 標準。
有了 STL,程序員就不必編寫大多數常用的數據結構和算法。而且 STL 是經過精心設計的,運行效率很高,比水平一般的程序員編寫的同類代碼速度更快。
有一種說法,C++ 是用來編寫大程序的,如果只是編寫幾十上百行的小程序,用C語言就可以,沒有必要用 C++。
這個說法是不準確的??梢哉f,寫小程序沒必要用面向對象的方法,但是用 C++ 還是能夠帶來很大方便的,因為 C++ 中有 STL。哪怕編寫只有十幾行的程序,也可能會用到 STL 中提供的數據結構和算法。例如對數組排序,用 STL 中的 sort 算法往往只需要一條語句就能解決,而不用像調用C語言庫函數 qsort 那樣還要編寫比較函數。
以上就是C++ STL庫應用匯總的詳細內容,更多關于C++ STL庫應用集合的資料請關注腳本之家其它相關文章!

