排序指针列表时出现问题 [英] Problem sorting a list of pointers

查看:70
本文介绍了排序指针列表时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对指针列表进行排序(在我的情况下,每个指针的类型均为Job)我的意图是按作业的序列号对其进行排序

i am trying to sort a list of pointers (in my case each pointer is of type Job) my intention is to sort the jobs by their serial number

void Container::jobSort(list<Job*> &jobs) {
    sort(jobs.begin(), jobs.end(), jobSerialCompare);
 }

bool Container::jobSerialCompare(const Job *jobA,const Job *jobB) {

   return (jobA->getSn()<jobB->getSn());
 }

我得到的错误是:

error: no matching function for call to 'sort(std::_List_iterator<Job*>, std::_List_iterator<Job*>, <unresolved overloaded function type>)'
/usr/include/c++/4.2.1/bits/stl_algo.h:2852: note: candidates are: void std::sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_List_iterator<Job*>, _Compare = bool (Container::*)(const Job*, const Job*)]
make: *** [src/Container.o] Error 1

我设法通过如下更改代码来解决错误:

i managed to solve the error by changing the code as follows :

struct compare {
  bool operator()(const Job *jobA, const Job *jobB) {    return (jobA->getSn()<jobB->getSn());
 }
};

 void Container::jobSort(list<Job*> &jobs) {
    jobs.sort(compare());
 }

现在没有编译错误,但是我想知道我的初始步骤出了什么问题,感谢您的帮助,欢呼

no compilation error now but i'm wondering what is wrong with my initial steps, help is appreciated, cheers

编辑-非常感谢大家的帮助!所有不同的答案都有助于描绘出清晰的画面

EDIT - Thanks a lot for all the help everyone ! all the different answers helped paint a clearer picture

推荐答案

错误消息说明了一切.您正在尝试使用需要随机访问迭代器的sort()对列表进行排序.List仅支持双向迭代器,因此独立的sort()不起作用.这就是为什么必须对列表使用特定的算法的原因: list.sort();

The error message says it all. You are trying to sort a list with a sort() that expects a random access iterators. List supports only bidirectional iterators, so the stand-alone sort() doesn't work. That's why you must use a specific algorithms for lists: list.sort();

还有其他人发现了非静态比较器问题,该问题与您收到的消息无关(但仍必须解决).

Also others spotted the non-static comparator issue, which is unrelated to the message you've got (but still must be fixed).

这篇关于排序指针列表时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆