![](/img/trans.png)
[英]using custom comparator for STL SET inside class through function pointer
[英]How to use custom class pointer comparator inside class being compared
我正在嘗試使用自定義比較器,如下面的最小示例所示:
#include <set>
using namespace std;
struct idComp;
class TestClass
{
public:
int id;
void setId(int i){ id = i; }
int getId(){ return id; }
void test( set<TestClass*, idComp> &s){
//do my stuff
}
void test2(){
set <TestClass*, idComp> s;
}
};
struct idComp
{
bool operator() (TestClass* t1, TestClass* t2) const
{
return t1->getId() < t2->getId();
}
};
int main(int argc, char* argv[])
{
return 0;
}
...但是當我嘗試編譯時,出現以下與test
功能相關的錯誤:
comp_ref.cpp:12:34: error: ‘idComp’ was not declared in this scope
void test( set<TestClass*, idComp> &s){
^~~~~~
comp_ref.cpp:12:40: error: template argument 2 is invalid
void test( set<TestClass*, idComp> &s){
加上test2
:
/usr/include/c++/7/bits/stl_tree.h:708:31: error: invalid use of incomplete type ‘struct idComp’
_Rb_tree_impl<_Compare> _M_impl;
關於如何/在何處定義idComp
以便函數test
可以使用它的任何建議?
由於您有一些循環依賴,您可以通過在TestClass
之前idComp
聲明idComp
來解決此問題:
struct idComp;
class TestClass
{
...
但是您可以將struct idComp
的定義保留在struct idComp
處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.