please look through the following program..
#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;
}
I am developing a B+ tree for a database engine for which i need a generic keyCompare method…Is this way of comparing byte streams by memcpy always the safe and foolproof 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? IS this fastest?
It doesn’t produce the correct result with integers and floats on little-endian architectures. And it can’t handle special floating point values like
infandnan.It should compare types using type-specific methods. For strings that involves using locales.