So I'd want to use a Set of char[4] so that I can store such arrays in it and check if an element is already in there. I began with C++ today so I definitely am not an expert. Here is what I've done for the moment :
struct Comparator {
bool operator()(unsigned char* s1, unsigned char* s2) const {
for (int i = 0; i < 4; ++i) {
if (s1[i] != s2[i]) {
return s1[i] < s2[i];
}
}
return false;
}
};
int main(int argc, const char* argv[]) {
set<unsigned char*, Comparator> setValues;
unsigned char *v1 = (unsigned char*) malloc(4);
unsigned char *v2 = (unsigned char*) malloc(4);
v1[0] = 'a';
v1[1] = 'b';
v1[2] = 'c';
v1[3] = 'd';
v1[0] = 'a';
v1[1] = 'b';
v1[2] = 'c';
v1[3] = 'd';
setValues.insert(v2);
printf("%lu\n", setValues.count(v1));
free(v1);
free(v2);
return EXIT_SUCCESS;
}
Unfortunately the output of this program is "0". Given that the chars between v1 and v2 are the same, I hoped that the output would be "1" (I inserted v2 and tried to find v1).
How can I do so that the set compares the values of the arrays (and not the pointer as it seems to do) ? I've searched and tried to overload operator "==" without success, and people seem to say that overloading "()" is enough...
Another thing : I'm also really not sur about the set allocation. I know that my set will have 100 arrays in it at the end of my program execution so I wonder if there is a way to directly allocate 100 * char[4] for the set ?
Thank you very much!