class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
vector<int> re;
for(int i=0;i<nums1.size();i++){
auto it2=find(nums2.begin(),nums2.end(),nums1[i]);
int y=it2-nums2.begin();
auto it=find_if(nums2.begin()+y, nums2.end(), bind2nd(greater<int>(), nums1[i]));
int x=it-nums2.begin();
if(x>=nums2.size()) re.push_back(-1);
else re.push_back(nums2[x]);
}
return re;
}
};
find()函数与find_if()返回的均为地址;-vector.begin()得到元素i的坐标。
find(first,last,val); //first是容器的首迭代器,last是容器的末迭代器,val是询问的元素。这个函数是在数据量较小或在无法用更高效率的函数解决问题的题目上使用,它的最坏复杂度是O(n),效率比较低。
find_if(first,last,compare);//first为首迭代器,last为末迭代器,compare为比较函数。查找第一个满足某个条件的值(并不是等于val的元素的位置)的位置。
greater()表示内置类型从大到小排序,less()表示内置类型从小到大排序。
(仿函数/bind2nd): 仿函数(functors)其实就是重载了operator()的对象。仿函数可以与函数适配器搭配使用。例如我们如果要使用count_if算法来计算容器中大于10的元素的个数。如果我们使用greater作为判别式(二元),而count_if只接受一个一元判别式,这时候我们就需要搭配函数适配器一起使用了。
bind2nd可以将二元仿函数转化为一元仿函数。