Nav*_*een 0 c++ sorting stl functor
我有一个关于std :: sort算法的问题.这是我的测试代码:
struct MyTest
{
int m_first;
int m_second;
MyTest(int first = 0, int second = 0) : m_first(first), m_second(second)
{
}
};
int main(int argc,char *argv[])
{
std::vector<MyTest> myVec;
for(int i = 0; i < 10; ++i)
{
myVec.push_back(MyTest(i, i + 1));
}
//Sort the vector in descending order on m_first without using stand alone function or functors
return 0;
}
Run Code Online (Sandbox Code Playgroud)
是否可以在m_first不使用任何独立函数或仿函数的情况下对变量进行排序?另外,请注意我没有使用提升.
180*_*ION 10
是的,只要要排序的范围中的值类型具有operator <定义"严格弱排序"的值,也就是说,它可以用于MyTest正确地比较两个实例.你可以这样做:
class MyTest
{
...
bool operator <(const MyTest &rhs) const
{
return m_first<rhs.m_first;
}
};
Run Code Online (Sandbox Code Playgroud)