gpt4 book ai didi

c++ - 通用 keyCompare 方法

转载 作者:行者123 更新时间:2023-11-27 23:28:32 25 4
gpt4 key购买 nike

请看下面的程序..

#include <stdio.h>
#include <malloc.h>
#include <iostream>
#include <string.h>

using namespace std;

int main()
{
char *key1 = (char*)malloc(sizeof(char)*26);
char *key2 = (char*)malloc(sizeof(char)*26);


int intkey1 = 10;
int intkey2 = 10;

float floatkey1 = 13.5f;
float floatkey2 = 13.5f;

double doublekey1 = 18.5;
double doublekey2 = 18.5;

char charkey1[10] = "nikhil";
char charkey2[10] = "nikhil";

//cout<<sizeof(int)<<" "<<sizeof(float)<<" "<<sizeof(double)<<endl;

memcpy(key1,&intkey1,sizeof(int));
memcpy(key2,&intkey2,sizeof(int));

int offset = sizeof(int);

memcpy(&key1[offset],&floatkey1,sizeof(float));
memcpy(&key2[offset],&floatkey2,sizeof(float));

offset = offset + sizeof(float);

memcpy(&key1[offset],&doublekey1,sizeof(double));
memcpy(&key2[offset],&doublekey2,sizeof(double));

offset = offset + sizeof(double);

memcpy(&key1[offset],charkey1,sizeof(charkey1));
memcpy(&key2[offset],charkey2,sizeof(charkey2));


int diff = memcmp(key1,key2,26);
if( diff > 0)
cout<<"Key1 is greater than key2"<<endl;
else if(diff < 0)
cout<<"Key1 is smaller than key2"<<endl;
else
cout<<"Both keys are equal"<<endl;
}

我正在为数据库引擎开发一个 B+ 树,我需要一个通用的 keyCompare 方法...这种通过 memcpy 比较字节流的方法是否总是安全和万无一失的,或者我是否需要根据类型进行比较我从扫描数据库引擎中存在的列信息中获得的字符键中存在的字段?这是最快的吗?

最佳答案

Is this way of comparing byte streams by memcpy always the safe and foolproof

它不会在小端架构上使用整数和 float 生成正确的结果。而且它无法处理特殊的浮点值,如 infnan

or should i need to compare based on the types of the fields present in char key that i get from scanning column information present in the database engine?

它应该使用特定于类型的方法来比较类型。对于涉及使用语言环境的字符串。

关于c++ - 通用 keyCompare 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7608950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com