remove、bind、function<BOOL(CString)>、replace_if使用方法

remove配合erase使用,remove会删除所有的需要删除的元素,但会把删除的元素保存在最后一位。比如vector{1,2,3,1,2},删除1,后会变成vector{2,3,2,1},所以还需要erase删除最后一位元素,才能彻底删除干净

#include <iostream>
#include<vector>
using namespace std;
int main()
{
    vector<int> num{ 1,5,6,8,4,9,3,5,4,7,6,1,5,6,8,1,2,3 };
    std::cout << "num size is :"<<num.size() << endl;
    num.erase(std::remove(num.begin(), num.end(), 1), num.end());
    std::cout << "remove num size is :" << num.size() << endl;
    for (size_t i = 0; i < num.size(); i++)
    {
        std::cout << num[i];
    }
    std::cout << endl; 
}

function函数和bind的结合使用,bind用placeholders::_1占位符来表示参数的位置,bind的思想实际上是一种延迟计算的思想,将可调用对象保存起来,然后在需要的时候再调用。

#include <iostream>
#include<vector>
#include <functional>
using namespace std;

bool test(int a, int b)
{
    return a < b;
}
int main()
{
    function<bool(int)> fun = bind(test, placeholders::_1, 10);
    bool data = fun(5);
    cout << data << endl;
}

replace_if主要是做替换,比如想将元素中的某个元素全部替换成a,可以采用这方法

​
#include <iostream>
#include<vector>
#include <functional>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> num{ 1,2,3,6,5,1,4,7,5,1,6,4,2,3 };
    replace_if(num.begin(), num.end(), [](int data) {return data == 1; }, 10);
	for (size_t i = 0; i < num.size(); i++)
	{
		cout << num[i]<<"\t";
	}
}

​

猜你喜欢

转载自blog.csdn.net/qq_38409301/article/details/121026404
今日推荐