Wil*_*ill 0 c c++ sorting performance stl
我有一个缓冲区,并有几个指针.我想根据指向的缓冲区中的字节对指针进行排序.
可以为qsort()和stl :: sort()提供自定义比较函数.例如,如果缓冲区为零终止,我可以使用strcmp:
int my_strcmp(const void* a,const void* b) {
const char* const one = *(const char**)a,
const two = *(const char**)b;
return ::strcmp(one,two);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果缓冲区不是零终止,我必须使用需要长度参数的memcmp().
在没有全局变量的情况下,是否有一种整齐有效的方法可以将缓冲区的长度放入我的比较函数中?
使用std :: sort,您可以使用这样的Functor:
struct CompString {
CompString(int len) : m_Len(len) {}
bool operator<(const char *a, const char *b) const {
return std::memcmp(a, b, m_Len);
}
private:
int m_Len;
};
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
std::sort(begin(), end(), CompString(4)); // all strings are 4 chars long
Run Code Online (Sandbox Code Playgroud)
编辑:从评论建议(我猜两个字符串都在一个公共缓冲区?):
struct CompString {
CompString (const unsigned char* e) : end(e) {}
bool operator()(const unsigned char *a, const unsigned char *b) const {
return std::memcmp(a, b, std::min(end - a, end - b)) < 0;
}
private:
const unsigned char* const end;
};
Run Code Online (Sandbox Code Playgroud)