#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
struct cmp {
bool operator()(const int& i, const int& j) const{
return false;
}
} ;
struct cmp2 {
bool operator()(const int& i, const int& j) const{
return false;
}
} cmp2_item;
class Solution {
public:
vector<int> smth(vector<int> arr, int k) {
// nth_element(arr.begin(), arr.begin()+k, arr.end(), cmp); #ERROR
// nth_element(arr.begin(), arr.begin()+k, arr.end(), cmp()); #WORKS
// nth_element(arr.begin(), arr.begin()+k, arr.end(), cmp2_item); # WORKS
// sort(arr.begin(), arr.end(), cmp); #ERROR
// sort(arr.begin(), arr.end(), cmp()); #WORKS
// set<int, cmp> s; # WORKS
// set<int, cmp2_item> s; # ERROR
return {};
}
};
int main() {
// your code goes here
Solution s;
s.smth({}, 1);
return 0;
}
我想了解为什么此代码以这种方式运行。对于nth_element,我们期望使用
有人可以使用签名来说明为什么吗?
nth_element :
template< class RandomIt, class Compare > void nth_element ( RandomIt first, RandomIt nth, RandomIt last, Compare comp );
排序 void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
设置: class Compare = less<T>, // set::key_compare/value_compare
class Alloc = allocator<T> // set::allocator_type
> class set;
最佳答案
其中的一部分是cmp2_item
不是类型,它是cmp2类型的实例。因此,您不能将其作为类类型传递。您可能可以执行以下操作:
set<int, cmp> s; //# WORKS
set<int, decltype(cmp2_item)> s2; //# NOW WORKS
对于这些: // Not ok because cmp is not a function comparison object, its a type
nth_element(arr.begin(), arr.begin()+k, arr.end(), cmp); #ERROR
// Ok because this is effectively passing a functor (and not just a type)
// I believe this takes a copy of the functor type (by construction), I
// am not quite so clear on the inner workings of the compiler in this
// case. I guess its by type comparison, but possible compiler
// implementation specific?
nth_element(arr.begin(), arr.begin()+k, arr.end(), cmp()); #WORKS
// This is ok because it passes an actual comparison object (that has
// operator () defined).
nth_element(arr.begin(), arr.begin()+k, arr.end(), cmp2_item); # WORKS
基本上,您必须更仔细地查看所传递的内容:类型,对象或函数-以及特定的STL作为参数接受的内容。注意:
comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if the first argument is less than (i.e. is ordered before) the second.
看到这里:enter link description here
关于c++ - C++仿函数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62978669/