C++ STL库应用汇总

时间:2022-09-19 13:45:57

1、std::max_element的使用

std::min_element类似,求最小

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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();
}

升级可以用到任务队列管理中,通过任务优先级,选择优先级最高的任务

?
1
2
3
4
5
6
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 主持开发,于 1998 年被加入 C++ 标准。

有了 STL,程序员就不必编写大多数常用的数据结构和算法。而且 STL 是经过精心设计的,运行效率很高,比水平一般的程序员编写的同类代码速度更快。

有一种说法,C++ 是用来编写大程序的,如果只是编写几十上百行的小程序,用C语言就可以,没有必要用 C++。

这个说法是不准确的。可以说,写小程序没必要用面向对象的方法,但是用 C++ 还是能够带来很大方便的,因为 C++ 中有 STL。哪怕编写只有十几行的程序,也可能会用到 STL 中提供的数据结构和算法。例如对数组排序,用 STL 中的 sort 算法往往只需要一条语句就能解决,而不用像调用C语言库函数 qsort 那样还要编写比较函数。

以上就是C++ STL库应用汇总的详细内容,更多关于C++ STL库应用集合的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/zx-hit/p/12418692.html