[英]C++ functors behavior
#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 : 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 類型的實例。 因此,您不能將其作為 class 類型傳遞。 你也許可以這樣做:
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
基本上你必須更仔細地查看你傳遞的內容:一個類型,一個 object 或一個 function - 以及特定的 STL 接受什么作為參數。
筆記:
比較 function object(即滿足比較要求的 object)如果第一個參數小於(即在第二個之前排序)則返回 true。
請參閱此處:在此處輸入鏈接描述
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.