下面是我的代码:
typedef struct
{
unsigned page;
unsigned slot;
} RID;
//Below struct has the Key on which I want to apply the sorting
struct LeafDataEntry
{
void *key;
RID rid;
};
//This is the sorting function I am using
bool leadNode_Key_asc( const LeafDataEntry &a, const LeafDataEntry &b){
return strcoll((char *)a.key, (char *)b.key) > 0;
//(strcmp((char *)a.key, (char *)b.key) > 0);
}
int main(){
vector<LeafDataEntry> lde;
char a[4] = {'D', 'B', 'C', 'D'};
RID aRID = {0,0};
char b[4] = {'A', 'C', 'B', 'A'};
RID bRID = {0,1};
unsigned size = sizeof(unsigned);
lde.resize(2);
char *tempPtr = (char *)malloc(8 + sizeof(RID));
memcpy(tempPtr, &size, 4);
tempPtr += 4;
memcpy(tempPtr, a, 4);
tempPtr -= 4;
lde[0].key = malloc(8);
memcpy(lde[0].key, tempPtr, 8);
memcpy(&lde[0].rid, &aRID, sizeof(RID));
memcpy(tempPtr, &size, 4);
tempPtr += 4;
memcpy(tempPtr, b, 4);
tempPtr -= 4;
lde[1].key = malloc(8);
memcpy(lde[1].key, tempPtr, 8);
memcpy(&lde[1].rid, &bRID, sizeof(RID));
std::sort(lde.begin(), lde.end(), leadNode_Key_asc);
cout << "Sorted Data :: " << endl;
for(int j=0; j<2; j++){
cout << "KEY :: " << (char *)(lde[j].key);
cout << ", RID ::" << "{" << lde[j].rid.pageNum << ", " <<
lde[j].rid.slotNum << "}";
}
return 0;
}
我想根据 *key 值对上面的 lde vector 进行排序。它不适用于上面给出的方式。
注意:我无法更改上面列出的任何结构的数据类型。
最佳答案
您的代码中有两个问题:
首先,您将 LeafDataEntry 的键中的字符串保存为 [4 个字节的字符串大小] + [字符串],但 strcoll 接受以 '\0' 结尾的字符串,并且没有大小引导它们,正如您所说的那样不希望您的数据类型发生任何更改,这可以解决您的问题:
bool leadNode_Key_asc( const LeafDataEntry &a, const LeafDataEntry &b){
size_t size1 = *(unsigned*)(a.key), size2 = *(unsigned*)(b.key);
string a1 = string((char*)a.key + 4, size1), a2 = string((char*)b.key + 4, size2);
return a1 < a2;
}
第二,这两行:
cout << ", RID ::" << "{" << lde[j].rid.pageNum << ", " <<
lde[j].rid.slotNum << "}";
应替换为:
cout << ", RID ::" << "{" << lde[j].rid.page << ", " <<
lde[j].rid.slot << "}";
关于c++ - 对具有指针的结构 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13407853/