码迷,mamicode.com
首页 > 编程语言 > 详细

C++使用谓词函数

时间:2020-04-05 00:40:25      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:seve   com   ISE   call   sorted   after   http   ace   name   

源码示例:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class IsEven
{
public:
  bool operator()(int x)
  {
    return x % 2 == 0;
  }
};

class LessThan
{
public:
  bool operator()(int a, int b)
  {
    return a < b;
  }
};

int main()
{
  int arr[] {12,25,36,8,11,15,89,32,71};
  vector<int> vec{12,25,36,8,11,15,89,32,71};

  cout<<"Original form of both array and vector:\n";
  for(int e:arr)
  {
    cout<<e<<" ";
  }

  //sort the array
  sort(begin(arr), end(arr),LessThan());

  //print the sorted array
  cout<<"\nHere is the aorted array:\n";
  for(int e:arr)
  {
    cout<<e<<" ";
  }

  //Call remove_if for even values
  auto start_removed = remove_if(begin(vec), end(vec), IsEven());
  cout<<"\nHere is the vector after call to remove_if:\n";
  for(int e:vec)
  {
    cout<<e<<" ";
  }

  //Erase the remove_if‘d elements
  vec.erase(start_removed, end(vec));
  cout<<"\nHere is the vector after call to erase:\n";
  for(int e:vec)
  {
    cout<<e<<" ";
  }
  cout<<endl;

  return 0;

}

 

结果展示:

技术图片

 

C++使用谓词函数

标签:seve   com   ISE   call   sorted   after   http   ace   name   

原文地址:https://www.cnblogs.com/ruigelwang/p/12635341.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!