Recently, i'm using a code to make unique int number for my classes.

I used reinterpret_cast<int>(my_unique_name) where my_unique_name is a char [] variable with unique value. Something like below:

const char my_unique_name[] = "test1234";

int generate_unique_id_from_string(const char *str)
{
  return reinterpret_cast<int>(str);
}

My question is, is the generated int really unique for all entry strings ?

有帮助吗?

解决方案

No, it is not. You are casting the address of the string, not its contents.

To create a numeric value based on string input, use a hash function. However, this doesn't create a truly unique number, because of the so-called pigeonhole principle.

其他提示

It would depend. Here's my interpretation of your question:

You're trying to assign a different number to each string. And identical strings from different sources will have different IDs.

Case 1:

If str happens to be a reusable buffer that you use to read in those strings from wherever. Then they'll all have the same base address. So no it will not be unique.

Case 2:

str happens to be a heap-allocated string. Furthermore, all the strings that will be ID'ed have overlapping lifetimes. Then yes, the IDs will be unique because they all reside in memory at the same time at different addresses.

EDIT:

If you want to generate a unique ID, but you want identical strings to have the same ID, then look at Greg's answer for a hash function.

It may not be always unique,

id1 = generate_unique_id_from_string("test12344444444444444");
id2 = generate_unique_id_from_string("Test12344444444444444");

Also, I think this will depend on the endianness of the platform.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top