STL: bind1st, find_if

还是Remove Duplicates from Sorted Array那道题,STL还有第二种方法(简直。。。)

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        return removeDuplicates(A, A + n, A) - A;
    }
template<typename InIt, typename OutIt>
OutIt removeDuplicates(InIt first, InIt last, OutIt output) {
    while (first != last) {
        *output++ = *first;
        first = find_if(first, last, bind1st(not_equal_to<int>(), *first));
    }
    return output;
}
}                    

又是两个不熟悉的函数:

bind1st

这个居然看cplusplus上的解释不太明白,又搜了一下,终于发现了个能看懂的(from:http://www.programlife.net/stl-bind1st-bind2nd-demo.html)

STL bind1st bind2nd详解

先不要被吓到,其实这两个配接器很简单。
首先,他们都在头文件<functional>中定义。
其次,bind就是绑定的意思,而1st就代表first,2nd就代表second,现在名在可以很快记住了。
再次,他们的申明是一样的,都是(const Operation& op, const T& x)

简单的说,bind1st(const Operation& op, const T& x)就是这么一个操作:x op value,而bind2nd(const Operation& op, const T& x)就是这么一个操作:value op x,其中value是被应用bind的对象。这两个配接器都用于将一个二元算子转换成一个一元算子。下面来看一段代码吧!//Coded by www.programlife.net#include <iostream>#include <functional>#include <algorithm>

#include <vector>
using namespace std;

int main()
{
	vector<int> coll;
	for(int i = 1; i <= 10; ++i)
	{
		coll.push_back(i);
	}
	//查找元素值大于10的元素的个数
	//也就是使得10 < elem成立的元素个数
     //补充一下,这里10相当于上面解释里的x,coll数组里的元素就是value int res = count_if(coll.begin(), coll.end(), bind1st(less<int>(), 10));
cout << res << endl; //查找元素值小于10的元素的个数 //也就是使得elem < 10成立的元素个数 res = count_if(coll.begin(), coll.end(), bind2nd(less<int>(), 10)); cout << res << endl; return 0; }

程序的输出结果是0 9

 

find_if:

template <class InputIterator, class UnaryPredicate>
   InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);

Returns an iterator to the first element in the range [first,last) for which pred returns true. If no such element is found, the function returns last.

所以对应到最上面leetcode的solution,返回的也就是第一个和first指向的元素不相同的迭代器。

原文地址:https://www.cnblogs.com/parapax/p/3633599.html