gpt4 book ai didi

c++ - 使用函数对象按降序对包含模板用户定义类的 STL vector 进行排序

转载 作者:行者123 更新时间:2023-11-28 02:21:07 25 4
gpt4 key购买 nike

我在对用户定义对象的 vector 进行排序时遇到问题。我正在使用 STL 定义的排序算法并将它传递给我的函数对象,但它拒绝编译,请你帮我解决这个问题。

谢谢。

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

template<typename T>
class MyType
{
public:
T t1;
public:
MyType()
{

}
MyType(const MyType& mt)
{
t1 = mt.t1;
}
MyType& operator=(const MyType& mt)
{
this->t1 = mt.t1;
return *this;
}
bool operator<(const MyType& mt)
{
if(this->t1 < mt.t1)
return true;
else
return false;
}
bool operator==(const MyType& mt)
{
if(this->t1 == mt.t1)
return true;
else
return false;
}
MyType(T t)
{
t1 = t;
}
};

template<class T>
class cmp_greater
{
public:
bool operator()(const T& a, const T& b)
{
return !(a < b);
}
};

int main()
{
MyType<int> m1(1);
MyType<int> m2(2);
MyType<int> m3(3);

vector<MyType<int> > vmt;

vmt.push_back(m1);
vmt.push_back(m2);
vmt.push_back(m3);

vector<MyType<int> >::iterator pos;

for(pos = vmt.begin(); pos != vmt.end(); pos++)
{
cout<<pos->t1<<endl;
}

sort(vmt.begin(), vmt.end(), cmp_greater<MyType<int> >() );
cout<<"After sorting in decending order."<<endl;
for(pos = vmt.begin(); pos != vmt.end(); pos++)
{
cout<<pos->t1<<endl;
}

vmt.erase(vmt.begin()+1);

cout<<"after erase"<<endl;

for(pos = vmt.begin(); pos != vmt.end(); pos++)
{
cout<<pos->t1<<endl;
}

//insert can also be used in vectors;
}

最佳答案

bool operator<(const MyType& mt)

它应该像const一样声明

bool operator<(const MyType& mt) const

否则,bool cmp_greater::operator()(const T& a, const T& b) 无法调用重载的小于运算符。

关于c++ - 使用函数对象按降序对包含模板用户定义类的 STL vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32431740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com