使用自定义比较器的std :: list :: sort错误(预期在')'令牌之前的主表达式) [英] Error in std::list::sort with custom comparator (expected primary-expression before ')' token)

查看:211
本文介绍了使用自定义比较器的std :: list :: sort错误(预期在')'令牌之前的主表达式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题是主要问题.确切的情况(我正在使用命名空间std;"):

The title is the main question. The exact scenario (I am 'using namespace std;'):

void SubstringMiner::sortByOccurrence(list<Substring *> & substring_list) {
   list::sort(substring_list.begin(), substring_list.end(), Substring::OccurrenceComparator);
}

这是比较器的定义:

class Substring {
    // ...
    class OccurrenceComparator {
        public:
            bool operator() (Substring * a, Substring *b);
    }
};

比较器的实现是直观而琐碎的.我还在std :: set中使用了非常类似的比较器,并且工作正常.当我添加sortByOccurrence()函数时,会出现标题错误.

Implementation of the comparator is intuitive and trivial. I am also using a very similar comparator in a std::set and it works fine. When I add the sortByOccurrence() funcion it gives me the error in the title.

我该怎么办?

编辑:我现在正尝试将Substring :: OccurrenceComparator()用作比较器,并收到以下错误消息:

I'm now trying to pass Substring::OccurrenceComparator() as the comparator, and am getting the following error:

g++ -Wall -g -c substring_miner.cpp -o obj/subtring_miner.o
substring_miner.cpp: In function ‘void SubstringMiner::sortByOccurrence(std::list<Substring*, std::allocator<Substring*> >&)’:
substring_miner.cpp:113: error: no matching function for call to ‘std::list<Substring*, std::allocator<Substring*> >::sort(std::_List_iterator<Substring*>, std::_List_iterator<Substring*>, Substring::OccurrenceComparator)’
/usr/include/c++/4.3/bits/list.tcc:303: note: candidates are: void std::list<_Tp, _Alloc>::sort() [with _Tp = Substring*, _Alloc = std::allocator<Substring*>]
make: *** [substring_miner] Error 1

我的代码行现在是:

list<Substring *>::sort(substring_list.begin(), substring_list.end(), Substring::OccurrenceComparator());

我无法删除模板,否则给我一个错误,提示模板参数错误.

I can't remove the template or it gives me an error saying that template parameters were wrong.

推荐答案

list成员sort是非静态函数,因此必须在列表实例上调用.

list member sort is a non-static function so must be called on a list instance.

substring_list.sort( Substring::OccurrenceComparator() );

编辑:您不能使用免费功能std::sort,因为它需要随机访问迭代器,而list迭代器则不需要.

You can't use the free function std::sort as it requires random access iterators which list iterators are not.

这篇关于使用自定义比较器的std :: list :: sort错误(预期在')'令牌之前的主表达式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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