我正在解決 leetcode OJ 上的一個問題,我必須在 C 中使用自定義比較器進行設定。
typedef pair<pair<int,int>,int> ppi;
class comp
{
public:
bool operator()(const ppi & p1, const ppi & p2)
{
if(p1.first.first == p2.first.first)
{
if(p1.first.second == p2.first.second) return p1.second > p2.second;
else return p1.first.second > p2.first.second;
}
else
return p1.first.first > p2.first.first;
}
};
當我試圖從集合中洗掉一個元素時,這給了我一個錯誤,它看起來像:
set<ppi, comp> customStack;
.
.
.
customStack.erase({{currentFrequency, currentAddress},val});
錯誤:
In file included from prog_joined.cpp:1:
In file included from ./precompiled/headers.h:50:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/map:60:
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_tree.h:779:4: error: static_assert failed due to requirement 'is_invocable_v<const comp &, const std::pair<std::pair<int, int>, int> &, const std::pair<std::pair<int, int>, int> &>' "comparison object must be invocable as const"
static_assert(
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_tree.h:1997:31: note: in instantiation of member function 'std::_Rb_tree<std::pair<std::pair<int, int>, int>, std::pair<std::pair<int, int>, int>, std::_Identity<std::pair<std::pair<int, int>, int>>, comp, std::allocator<std::pair<std::pair<int, int>, int>>>::_S_key' requested here
if (_M_impl._M_key_compare(_S_key(__x), __k))
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_tree.h:2534:38: note: in instantiation of member function 'std::_Rb_tree<std::pair<std::pair<int, int>, int>, std::pair<std::pair<int, int>, int>, std::_Identity<std::pair<std::pair<int, int>, int>>, comp, std::allocator<std::pair<std::pair<int, int>, int>>>::equal_range' requested here
pair<iterator, iterator> __p = equal_range(__x);
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_set.h:685:21: note: in instantiation of member function 'std::_Rb_tree<std::pair<std::pair<int, int>, int>, std::pair<std::pair<int, int>, int>, std::_Identity<std::pair<std::pair<int, int>, int>>, comp, std::allocator<std::pair<std::pair<int, int>, int>>>::erase' requested here
{ return _M_t.erase(__x); }
^
Line 39: Char 25: note: in instantiation of member function 'std::set<std::pair<std::pair<int, int>, int>, comp, std::allocator<std::pair<std::pair<int, int>, int>>>::erase' requested here
customStack.erase({{currentFrequency, currentAddress},val});
^
1 error generated.
在比較器中添加“const”后(第 4 行):
class comp
{
public:
bool operator()(const ppi & p1, const ppi & p2)const
這對我有用。
添加額外關鍵字的原因是什么?
uj5u.com熱心網友回復:
通過將其添加const到該成員函式的末尾,您將使其成為 const 成員函式,這意味著它不可能修改您的任何成員變數。因為呼叫非 const 成員函式可以修改物件,所以如果物件是 const,則不能呼叫它。
std::set的擦除成員函式要求 operator() 是 const 以阻止它在您沒有意識到的情況下修改其集合中的物件。
如果任何成員函式可以是 const,那么它應該是 const,就像您宣告或作為引數接受的任何變數一樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448848.html
上一篇:shared_ptra=make_shared()是否在建構式運行之前創建shared_ptr的副本?
下一篇:MySQL:提取唯一日期
