【问题标题】:Can i sort structure in c++ using stl sort我可以使用 stl sort 在 C++ 中对结构进行排序吗
【发布时间】:2012-10-31 11:53:13
【问题描述】:

我试图在 C++ 中使用 stl sort 对结构进行排序。但我得到了一些错误。是我们无法使用 stl sort 对 c++ 中的结构进行排序,还是我在实现上的错,如果是我的错,请告诉我更正。

这是代码(它非常小:))

#include<iostream>
#include<algorithm>
using namespace std;
struct log {
       int sd;
       int ed;
} log[1000];
bool key(int i,int j) {
 return (log[i].ed<log[j].ed);
}
int main() {
int n,i;
cin>>n;
sort(log,log+n,key);
for (i=0;i<n;i++) cin>>log[i].sd>>log[i].ed;
for (i=0;i<n;i++) cout<<log.sd<<","<<log.ed<<endl;
system("PAUSE");
}

【问题讨论】:

    标签: sorting stl structure


    【解决方案1】:

    是的,你可以。但是你的比较器应该有两个const log &amp;(不是int)参数。

    【讨论】:

    • 嗯...我是 C++ 的初学者,能告诉我更多我应该把 'const log &' 放在哪里吗?
    • @ManasVerma bool key(const log &amp;a, const log &amp;b) { return (a.ed &lt; b.ed); }
    • 顺便说一句。在这种情况下,大多数人更喜欢使用仿函数(函数对象)而不是常规函数,尽管后者也可以。
    • 我按照你说的进行了编辑,但它仍然会给出错误 - “8 预期 ,' or ...' 在 '&' 令牌之前” & 还有更多错误,如 'a'、'b'未声明,“8ISO C++ forbids declaration of log' 没有类型”等!!!
    • @ManasVerma 哦,您应该重命名您的结构或数组。使用相同的名称会使编译器感到困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多