Ben*_*ves 5 c++ comparison list
如何将指向成员函数的指针传递给std :: list.sort()?
这可能吗?谢谢
struct Node {
uint32_t ID;
char * Value;
};
class myClass {
private:
uint32_t myValueLength;
public:
list<queueNode *> MyQueue;
bool compare(Node * first, Node * second);
bool doStuff();
}
bool myClass::compare(Node * first, Node * second) {
unsigned int ii =0;
while (ii < myValueLength)
{
if (first-> Value[ii] < second-> Value[ii])
{
return true;
} else if (first-> Value[ii] > second-> Value[ii])
{
return false;
}
++ii;
}
return false;
}
bool myClass::doStuff()
{
list.sort(compare);
}
Run Code Online (Sandbox Code Playgroud)
我想在类中使用长度变量,而不是在比较函数中使用strlen()(Value将始终具有相同的长度)
编辑:myValueLength不是我想从比较函数中访问的唯一变量我只是简化它以使示例更短.
阐述悲伤的反应,为什么不使用仿函数?例如:
struct Functor
{
bool operator()( char * a, char * b )
{ return strcmp(a,b) < 0; }
};
Run Code Online (Sandbox Code Playgroud)
然后你可以使用:
Functor f;
myList.sort(f);
Run Code Online (Sandbox Code Playgroud)
您甚至可以通过定义operator()来将您的类用作Functor ...
class myClass {
...
bool operator()( queueNode * a, queueNode * b )
{ return compare( a, b ); }
void doStuff() { MyQueue.sort(*this); }
};
Run Code Online (Sandbox Code Playgroud)
简单示例代码:
#include <iostream>
#include <list>
using namespace std;
// Assumes TYPE t; cout << t; is valid.
template<class TYPE>
inline ostream & operator<< ( ostream & theOstream,
const list<TYPE> & theList )
{
typename list<TYPE>::const_iterator listIterator = theList.begin();
for ( int i = 0; listIterator != theList.end(); listIterator ++, i ++ )
theOstream << " [" << i << "]: \"" << (*listIterator) << "\"" << endl;
return theOstream;
}
struct Functor
{
bool operator()( const char * a, const char * b )
{ return strcmp(a,b) < 0; }
};
int
main()
{
list<char*> l;
/* Load up some example test data... */
char s[3];
s[2] = '\0';
for ( s[0]='c'; s[0]>='a'; s[0]-- )
for ( s[1]='c'; s[1]>='a'; s[1]-- )
l.push_back(strdup(s));
/* Show us that test data... */
cout << l << endl;
/* Sort list. */
Functor f;
l.sort(f);
/* Show us what we have now... */
cout << l << endl;
}
Run Code Online (Sandbox Code Playgroud)
有可能的.你考虑过使用boost :: function吗?
list.sort( boost::bind( &myClass::compare, this, _1, _2 ) );
Run Code Online (Sandbox Code Playgroud)
您的"比较"功能是否依赖于此数据?如果不是 - 你可能会简单地将'比较'功能变为静态.然后它会
list.sort( &myClass::compare );
Run Code Online (Sandbox Code Playgroud)
您可以添加辅助结构来进行比较
list.sort( Comparer( myValueLength ) );
struct Comparer
{
Comparer( uint32_t myValueLength ):
length( myValueLength )
{}
bool operator() (Node * first, Node * second)
{
unsigned int ii =0;
while (ii < length)
{
if (first-> Value[ii] < second-> Value[ii])
{
return true;
} else if (first-> Value[ii] > second-> Value[ii])
{
return false;
}
++ii;
}
return false;
}
uint32_t length;
};
Run Code Online (Sandbox Code Playgroud)