STL中算法锦集(四)

文章目录

  • STL中算法锦集(四)
    • 一、< algorithm >
      • 1.std::is_permutation
      • 2.std::is_sorted
      • 3.std::is_sorted_until
      • 4.std::iter_swap
      • 5.std::lexicographical_compare
      • 6.std::lower_bound
      • 7.std::make_heap
      • 8.std::max_element

一、< algorithm >

1.std::is_permutation

  • 原型:
template <class ForwardIterator1, class ForwardIterator2>bool is_permutation (ForwardIterator1 first1, ForwardIterator1 last1,ForwardIterator2 first2);template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>bool is_permutation (ForwardIterator1 first1, ForwardIterator1 last1,ForwardIterator2 first2, BinaryPredicate pred);
  • 参数:
  • ForwardIterator1 first1:区间1的开始
  • ForwardIterator1 last1:区间1的结束
  • ForwardIterator2 first2: 区间2的开始
  • BinaryPredicate pred:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:用来检查一个序列是不是另一个序列的排列,
  • 返回值:如果是,会返回 true
  • 实现:
template <class InputIterator1, class InputIterator2>bool is_permutation (InputIterator1 first1, InputIterator1 last1,InputIterator2 first2)
{std::tie (first1,first2) = std::mismatch (first1,last1,first2);if (first1==last1) return true;InputIterator2 last2 = first2; std::advance (last2,std::distance(first1,last1));for (InputIterator1 it1=first1; it1!=last1; ++it1) {if (std::find(first1,it1,*it1)==it1) {auto n = std::count (first2,last2,*it1);if (n==0 || std::count (it1,last1,*it1)!=n) return false;}}return true;
}
  • 案例:
// is_permutation example
#include <iostream>     // std::cout
#include <algorithm>    // std::is_permutation
#include <array>        // std::arrayint main () {std::array<int,5> foo = {1,2,3,4,5};std::array<int,5> bar = {3,1,4,5,2};if ( std::is_permutation (foo.begin(), foo.end(), bar.begin()) )std::cout << "foo and bar contain the same elements.\n";return 0;
}Output:
foo and bar contain the same elements.

2.std::is_sorted

  • 原型:
template <class ForwardIterator>bool is_sorted (ForwardIterator first, ForwardIterator last);template <class ForwardIterator, class Compare>bool is_sorted (ForwardIterator first, ForwardIterator last, Compare comp);
  • 参数:
  • ForwardIterator first:区间的开始
  • ForwardIterator last:区间的结束
  • Compare comp:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:判断[first,last)区间内的元素是否满足comp的排序规则
  • 返回值:是返回true
  • 实现:
template <class ForwardIterator>bool is_sorted (ForwardIterator first, ForwardIterator last)
{if (first==last) return true;ForwardIterator next = first;while (++next!=last) {// or, if (comp(*next,*first))if (*next<*first)     return false;++first;}return true;
}
  • 案例:
// is_sorted example
#include <iostream>     // std::cout
#include <algorithm>    // std::is_sorted, std::prev_permutation
#include <array>        // std::arrayint main () {std::array<int,4> foo {2,4,1,3};do {// try a new permutation:std::prev_permutation(foo.begin(),foo.end());// print range:std::cout << "foo:";for (int& x:foo) std::cout << ' ' << x;std::cout << '\n';} while (!std::is_sorted(foo.begin(),foo.end()));std::cout << "the range is sorted!\n";return 0;
}Output:
foo: 2 3 4 1
foo: 2 3 1 4
foo: 2 1 4 3
foo: 2 1 3 4
foo: 1 4 3 2
foo: 1 4 2 3
foo: 1 3 4 2
foo: 1 3 2 4
foo: 1 2 4 3
foo: 1 2 3 4
the range is sorted!

3.std::is_sorted_until

  • 原型:
template <class ForwardIterator>ForwardIterator is_sorted_until (ForwardIterator first, ForwardIterator last);template <class ForwardIterator, class Compare>ForwardIterator is_sorted_until (ForwardIterator first, ForwardIterator last,Compare comp);
  • 参数:
  • ForwardIterator first:区间的开始
  • ForwardIterator last:区间的结束
  • Compare comp:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:能检测出[first,last)区间是否满足come规则有序
  • 返回值:还会返回一个正向迭代器,该迭代器指向的是当前序列中第一个破坏有序状态的元素。
  • 实现:
template <class ForwardIterator>ForwardIterator is_sorted_until (ForwardIterator first, ForwardIterator last)
{if (first==last) return first;ForwardIterator next = first;while (++next!=last) {if (*next<*first) return next;++first;}return last;
}
  • 案例:
// is_sorted_until example
#include <iostream>     // std::cout
#include <algorithm>    // std::is_sorted_until, std::prev_permutation
#include <array>        // std::arrayint main () {std::array<int,4> foo {2,4,1,3};std::array<int,4>::iterator it;do {// try a new permutation:std::prev_permutation(foo.begin(),foo.end());// print range:std::cout << "foo:";for (int& x:foo) std::cout << ' ' << x;it=std::is_sorted_until(foo.begin(),foo.end());std::cout << " (" << (it-foo.begin()) << " elements sorted)\n";} while (it!=foo.end());std::cout << "the range is sorted!\n";return 0;
}Output:
foo: 2 3 4 1 (3 elements sorted)
foo: 2 3 1 4 (2 elements sorted)
foo: 2 1 4 3 (1 elements sorted)
foo: 2 1 3 4 (1 elements sorted)
foo: 1 4 3 2 (2 elements sorted)
foo: 1 4 2 3 (2 elements sorted)
foo: 1 3 4 2 (3 elements sorted)
foo: 1 3 2 4 (2 elements sorted)
foo: 1 2 4 3 (3 elements sorted)
foo: 1 2 3 4 (4 elements sorted)
the range is sorted!

4.std::iter_swap

  • 原型:
template <class ForwardIterator1, class ForwardIterator2>void iter_swap (ForwardIterator1 a, ForwardIterator2 b);
  • 参数:
  • ForwardIterator1 a:区间的开始
  • ForwardIterator1 b:区间的结束
  • 作用:交换a,b两个迭代器的元素内容
  • 返回值:没有返回值
  • 实现:
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;
}Output:
myvector contains: 10 99 40 99

5.std::lexicographical_compare

  • 原型:
template <class InputIterator1, class InputIterator2>bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1,InputIterator2 first2, InputIterator2 last2);template <class InputIterator1, class InputIterator2, class Compare>bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1,InputIterator2 first2, InputIterator2 last2,Compare comp);
  • 参数:
  • InputIterator1 first1:区间1的开始
  • InputIterator1 last1:区间1的结束
  • InputIterator2 first2:区间2的开始
  • InputIterator2 last2:区间2的结束
  • Compare comp:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:求[first1,last1)区间的字典序是否小于[first2,last2)区间的元素
  • 返回值:是就返回true
  • 实现:
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;
}Output:
Comparing foo and bar lexicographically (foo<bar):
Using default comparison (operator<): true
Using mycomp as comparison object: false

6.std::lower_bound

  • 原型:
template <class ForwardIterator, class T>ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,const T& val);template <class ForwardIterator, class T, class Compare>ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,const T& val, Compare comp);
  • 参数:
  • ForwardIterator first:区间的开始
  • ForwardIterator last:区间的结束
  • const T& val:
  • Compare comp:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:在first和last中的前闭后开区间进行二分查找
  • 返回值:返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置.
  • 实现:
template <class ForwardIterator, class T>ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val)
{ForwardIterator it;iterator_traits<ForwardIterator>::difference_type count, step;count = distance(first,last);while (count>0){it = first; step=count/2; advance (it,step);if (*it<val) {                 // or: if (comp(*it,val)), for version (2)first=++it;count-=step+1;}else count=step;}return first;
}
  • 案例:
// lower_bound/upper_bound example
#include <iostream>     // std::cout
#include <algorithm>    // std::lower_bound, std::upper_bound, std::sort
#include <vector>       // std::vectorint main () {int myints[] = {10,20,30,30,20,10,10,20};std::vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20std::sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30std::vector<int>::iterator low,up;low=std::lower_bound (v.begin(), v.end(), 20); //          ^up= std::upper_bound (v.begin(), v.end(), 20); //                   ^std::cout << "lower_bound at position " << (low- v.begin()) << '\n';std::cout << "upper_bound at position " << (up - v.begin()) << '\n';return 0;
}Output:
lower_bound at position 3
upper_bound at position 6

7.std::make_heap

  • 原型:
template <class RandomAccessIterator>void make_heap (RandomAccessIterator first, RandomAccessIterator last);template <class RandomAccessIterator, class Compare>void make_heap (RandomAccessIterator first, RandomAccessIterator last,Compare comp );
  • 参数:
  • RandomAccessIterator first:区间的开始
  • RandomAccessIterator last:区间的结束
  • Compare comp:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:根据[first,last)区间的元素构建一个comp规则的堆

  • 返回值:没有返回值

  • 案例:

// range heap example
#include <iostream>     // std::cout
#include <algorithm>    // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector>       // std::vectorint main () {int myints[] = {10,20,30,5,15};std::vector<int> v(myints,myints+5);std::make_heap (v.begin(),v.end());std::cout << "initial max heap   : " << v.front() << '\n';std::pop_heap (v.begin(),v.end()); v.pop_back();std::cout << "max heap after pop : " << v.front() << '\n';v.push_back(99); std::push_heap (v.begin(),v.end());std::cout << "max heap after push: " << v.front() << '\n';std::sort_heap (v.begin(),v.end());std::cout << "final sorted range :";for (unsigned i=0; i<v.size(); i++)std::cout << ' ' << v[i];std::cout << '\n';return 0;
}Edit & RunOutput:
initial max heap   : 30
max heap after pop : 20
max heap after push: 99
final sorted range : 5 10 15 20 99

8.std::max_element

  • 原型:
template <class ForwardIterator>ForwardIterator max_element (ForwardIterator first, ForwardIterator last);template <class ForwardIterator, class Compare>ForwardIterator max_element (ForwardIterator first, ForwardIterator last,Compare comp);
  • 参数:
  • ForwardIterator first:区间的开始
  • ForwardIterator last:区间的结束
  • Compare comp:自定义比较规则,可以是函数指针或者仿函数对象、lambda表达式
  • 作用:求[first,last)区间内最大的元素
  • 返回值:返回区间内最大的元素的迭代器
  • 实现:
template <class ForwardIterator>ForwardIterator max_element ( ForwardIterator first, ForwardIterator last )
{if (first==last) return last;ForwardIterator largest = first;while (++first!=last)if (*largest<*first)    // or: if (comp(*largest,*first)) for version (2)largest=first;return largest;
}
  • 案例:
// min_element/max_element example
#include <iostream>     // std::cout
#include <algorithm>    // std::min_element, std::max_elementbool myfn(int i, int j) { return i<j; }struct myclass {bool operator() (int i,int j) { return i<j; }
} myobj;int main () {int myints[] = {3,7,2,5,6,4,9};// using default comparison:std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n';std::cout << "The largest element is "  << *std::max_element(myints,myints+7) << '\n';// using function myfn as comp:std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myfn) << '\n';std::cout << "The largest element is "  << *std::max_element(myints,myints+7,myfn) << '\n';// using object myobj as comp:std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myobj) << '\n';std::cout << "The largest element is "  << *std::max_element(myints,myints+7,myobj) << '\n';return 0;
}Edit & RunOutput:
The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9

STL中算法锦集(四)相关推荐

  1. STL中算法锦集(三)

    STL中算法锦集(三) 文章目录 STL中算法锦集(三) 一.< algorithm > 1.std::find_if 2.std::find_if_not 3.std::for_each ...

  2. STL中算法锦集(二)

    STL中算法锦集(二) 文章目录 STL中算法锦集(二) 一.< algorithm > 1.std::equal 2.std::equal_range 3.std::fill 4.std ...

  3. STL中算法锦集(一)

    STL中算法锦集(一) 文章目录 STL中算法锦集(一) 一.< algorithm > 1.std::adjacent_find 2.std::all_of 3.std::any_of ...

  4. 【数据结构与算法】二叉树基本算法锦集

    二叉树结点 public class BinaryTreeNode<T> {private T data;private BinaryTreeNode<T> left;priv ...

  5. [C++ STL] 常用算法总结

    1 概述 STL算法部分主要由头文件<algorithm>,<numeric>,<functional>组成.要使用 STL中的算法函数必须包含头文件<alg ...

  6. C++ STL 中提供的算法

    1 算法 1.1 for_each() 参数有三个: 首迭代器 尾迭代器 执行的函数 例如如下代码: #include <algorithm> //必须包含 #include <ve ...

  7. ptaa乘以b_PTA|团体程序设计天梯赛-练习题目题解锦集(C/C++)(持续更新中……)...

    C++ CPP C++语言开发 PTA|团体程序设计天梯赛-练习题目题解锦集(C/C++)(持续更新中--) PTA|团体程序设计天梯赛-练习题目题解锦集(持续更新中) 实现语言:C/C++:     ...

  8. SCPPO(十):网站发布中的问题锦集—手动发布网站

    [前言] 现在做的项目是个维护性的项目,我们是第三期的末尾,最近正忙着验收.当然在验收前会有些功能需要修改,另外也会有新的需求需要实现:再加之最近有企业核对数据等等,所以网站的发布变成主要的工作之一. ...

  9. PTA|团体程序设计天梯赛-练习题目题解锦集(C/C++)(持续更新中……)

    PTA|团体程序设计天梯赛-练习题目题解锦集(持续更新中) 实现语言:C/C++:      欢迎各位看官交流讨论.指导题解错误:或者分享更快的方法!! 题目链接:https://pintia.cn/ ...

最新文章

  1. Mac Pro 开机自启动 PHP-FPM,Nginx,MySql 等软件
  2. mybatis中传集合时 报异常 invalid comparison: java.util.Arrays$ArrayList and java.lang.String
  3. modulenotfounderror: no module 或modulenotfounderror: no module named 'matplotlib._path' 原因详解及解决办法
  4. POJ 1260 Pearls
  5. 猿团专访云信CTO阙杭宁——网易云信“稳定”背后的秘密
  6. RabbitMQ 消息队列六种模式
  7. blog被封了文章全被删除了,郁闷
  8. python io_NumPy IO
  9. 工业交换机那么贵,为什么那么多人都在用?
  10. scp构造端口_指定端口号的scp
  11. java 文件下载,中文表名,中文内容
  12. php隐藏做上传图片,php做图片上传功能
  13. 避障跟随测距c语言程序,红外避障小车c语言程序.pdf
  14. java guava 使用_使用Guava操作基本类型
  15. ecshop怎样在新主页模板里调用首页主广告
  16. 8.SOA架构:服务和微服务分析及设计--- Web服务及REST服务的服务API与契约版本控制
  17. 深度揭秘Greenplum数据库透明加密
  18. 机房环境监控报警系统
  19. 新1期_012课_内存控制器与SDRAM
  20. SQL Sever:关于外键引用无效表的问题

热门文章

  1. java版spring cloud+spring boot+redis多租户社交电子商务平台(三)SpringBoot用JdbcTemplates访问Mysql...
  2. VS2010 关于.wav音频文件播放
  3. tcp_handle_req: Made 4 read attempts but message is not complete yet - closing connection
  4. IE与Chrome对相对URL解析的区别
  5. JSP中 request.getRealPath(/xx/yy) 方法提示已经过时的替代方法
  6. spring mvc+junit
  7. C++虚函数与虚函数表
  8. iOS开发笔记[16/50]:Views
  9. 查看数据库系统字符集
  10. XML与JavaBean相互转换工具