<c++> lambda expressions and function objects

This article refers to

  1. Teacher Hou Jie's handout
  2. https://blog.csdn.net/KFLING/article/details/80187847

Example 1

Function object

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

using namespace std;

class LambdaFunctor {
    
    
public:
    bool operator()(char b) {
    
    
     return b == ' ';   
    }
};

int main()
{
    
    
	string s("Text with    spaces");
	cout << "删除之前"<< s << endl;
	s.erase(remove_if(s.begin(), s.end(), LambdaFunctor()), 
            s.end());
	cout <<"删除之后"<< s << endl;
	return 0;
}

lambda expression

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

using namespace std;

int main()
{
    
    
	string s("Text with    spaces");
	cout << "删除之前"<< s << endl;
	s.erase(remove_if(s.begin(), s.end(), 
                     [] (char x) {
    
    
                        return x == ' ';
                     }), 
            s.end());
	cout <<"删除之后"<< s << endl;
	return 0;
}

Ordinary function

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

using namespace std;
bool func(char x) {
    
    
    return x == ' ';   
}

int main()
{
    
    
	string s("Text with    spaces");
	cout << "删除之前"<< s << endl;
	s.erase(remove_if(s.begin(), s.end(), 
                      func), 
            s.end());
	cout <<"删除之后"<< s << endl;
	return 0;
}

Example 2

lambda expression

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

using namespace std;

int main()
{
    
    
    vector<int> vi {
    
    5, 28, 50, 83, 70, 590, 245, 59, 24};
    int x = 30;
    int y = 100;
    vi.erase(   remove_if(vi.begin(),
                          vi.end(),
                          [x, y](int n) {
    
    return x < n && n < y;}    
                        ),
                vi.end()
            );
    for(auto i : vi)
        cout << i << ' '; // 5 28 590 245 24
    cout << endl;
	return 0;
}

Results of the:

5 28 590 245 24 

Function object

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

using namespace std;

class LambdaFunctor {
    
    
public:
    LambdaFunctor(int a, int b) : m_a(a), m_b(b) {
    
    };
    bool operator()(int n) const {
    
    
        return m_a < n && n < m_b;
    };    
private:
    int m_a;
    int m_b;    
};

int main()
{
    
    
    vector<int> vi {
    
    5, 28, 50, 83, 70, 590, 245, 59, 24};
    int x = 30;
    int y = 100;
    vi.erase(   remove_if(vi.begin(),
                          vi.end(),
                          LambdaFunctor(x, y)  
                        ),
                vi.end()
            );
    for(auto i : vi)
        cout << i << ' '; // 5 28 590 245 24
    cout << endl;
	return 0;
}
5 28 590 245 24

Guess you like

Origin blog.csdn.net/gyhwind/article/details/115272808