std::sort 没有函子
我有一个关于 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;
}
是否可以在不使用任何独立函数或函子的情况下对变量 m_first
上的向量进行排序? 另外,请注意,我没有使用 boost。
I have a question regarding the std::sort algorithm. Here is my test code:
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;
}
Is it possible to sort the vector on the variable m_first
without using any stand alone functions or functors? Also, please note that I am not using boost.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该在
MyTest
中定义一个operator<
,它应该如下所示:You should define an
operator<
inMyTest
and it should look like this:http://ideone.com/3QLtP
这没有定义运算符 <,但定义了函子。
然而,穿越时空或编译过程是很有趣的。
http://ideone.com/3QLtP
This defines no operator <, but does define functor.
However, it's fun to travel through time or compilation process.
可以使用成员函数来完成此操作,但独立函数是最佳选择。
为什么 ..
It is possible to do it with a member function but the stand alone function is the way to go.
Why ..
写一个运算符< 为你的结构。 这是 sort 使用的默认函数,也是让它在自定义数据结构上运行的最简单方法。
Write an operator< for your struct. This is the default function used by sort and the easiest way to allow it to function on your custom data structures.
定义运算符<
Define the operator<
是的,只要要排序的范围内的值类型有一个
运算符<
定义了“严格弱排序”,也就是说可以用来比较两个MyTest
实例正确。 你可能会这样做:Yes, so long as the value type in the range to be sorted has an
operator <
that defines a "strict weak ordering", that is to say, it can be used to compare twoMyTest
instances correctly. You might do something like: