2009-07-08 24 views
1

标题是主要问题。确切的情况(我在 '使用命名空间std;'):std :: list :: sort与自定义比较器(预期的主表达式之前的')'令牌)的错误

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()函数时,它给了我标题中的错误。

我该怎么办?

编辑:我现在试图通过子串:: OccurrenceComparator()作为比较,并且正在以下错误:

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()); 

我无法删除该模板或它给我一个错误,说模板参数是错误的。

+0

其实没有。我们希望整个错误信息实际上包含有用的信息。 – 2009-07-08 21:52:15

+0

添加了整个错误消息 – 2009-07-08 21:56:09

+0

错误消息说,列表没有一个使用这些参数的sort()方法。尝试substring_list。排序(子串:: OccurrenceComparator()); – 2009-07-08 22:00:29

回答

4

list成员sort是一个非静态的功能,所以必须在列表实例调用。

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

编辑:,因为它需要随机访问迭代器,其list迭代器是不是不能使用免费的功能std::sort

4

您正在通过作为函数的参数。你不能做到这一点 - 你必须创建类的实例,并传递:

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

注意额外的括号OccurenceComparator后上面创建使用默认构造函数类的临时对象。

另一个错误是,您将list::sort作为类std::list上的静态函数调用。这不是静态的,所以你需要在substring_list上将它称为成员函数。

+0

请检查问题编辑。 – 2009-07-08 21:48:39

3

上面的Pavel Minaev已经解决了原始问题。
但一些额外的笔记。

运算符()应该可能是const(以及参数)。
对于像这样的简单类来说,使它们变成结构更简单。

struct OccurrenceComparator 
{ 
    bool operator() (Substring const* a, Substring const* b) const; 
}; 

注意的比较必须提供一个严格的弱序:

template<class BinaryPredicate>
void sort(BinaryPredicate comp);

Comp must be a comparison function that induces a strict weak ordering (as defined in the LessThan Comparable requirements on objects of type T. This function sorts the list *this according to Comp. The sort is stable, that is, the relative order of equivalent elements is preserved. All iterators remain valid and continue to point to the same elements. [6] The number of comparisons is approximately N log N, where N is the list's size.

相关问题