I am doing an program of Employee Database in C++. I want to generate a Unique Employee Number for each Employee but I am not successful can someone help me and oh please post the code relevant to Turbo C++ Borland and not Visual C++. Hoping to hear from you guys soon. If not the code please tell me an algorithm to do this job.
Asked
Active
Viewed 2,253 times
-6
-
8Sequential are known to be unique... – Luchian Grigore Oct 30 '12 at 16:56
-
Implementation of Luchian Grigore's algorithm. `last_id++;` If last_id is the last one used, this code will create a new unique id and store it in last_id. – BenjiWiebe Oct 30 '12 at 16:58
-
1If you are using a normal RDBMS back-end to store employee data in, you should perhaps use that database's own unique identifier generating mechanisms, as these can be enforced by the database and any locking and synchonrisation issues should be handled for you. If you are not using a standard database back end, you probably should be. – Rook Oct 30 '12 at 17:11
-
Please show us what you've already tried. – Gijs Overvliet Oct 30 '12 at 17:16
2 Answers
2
Start at 1 and increase each time. Here's a single-threaded version:
unsigned long long int unique_id()
{
static unsigned long long int n = 0;
return ++n;
}
For a thread-safe version, use an std::atomic<unsigned long long int>
instead, or add a mutex.

Kerrek SB
- 464,522
- 92
- 875
- 1,084
-
-
C++Builder, Turbo C++'s modern (and maintained) replacement, apparently supports at least some of the C++11 spec. Not much hope for Turbo C++ itself, however. – Rook Oct 30 '12 at 17:14
-1
A very simple unique ID generator
class UniqueIDGenerator{
private:
static unsigned long uniqueId = 1000ul; //Starting the IDs with 1000
public:
static unsigned long generateUniqueId(){
return uniqueId++;
}
};
Use it like this
int empId = UniqueIDGenerator::generateUniqueId();

Evan Teran
- 87,561
- 32
- 179
- 238

Vivek
- 1,640
- 1
- 17
- 34
-
@KerrekSB Sorry if I made any syntactical error. I have not touched C++ for a long time. Can you please point out the error, so that I can correct it? – Vivek Oct 30 '12 at 17:08
-
Well, there's no such thing as a "`public class`" in C++. Just `class`. But having a class with no non-static members is also a bit over the top. Why not just a function? – Kerrek SB Oct 30 '12 at 17:13
-
Or at least, make it an actual class with the ID seed as a construction property or something! – Rook Oct 30 '12 at 17:15
-
Thanks for the correction. I agree to the point of not needing a class here when there is no non static member :) – Vivek Oct 30 '12 at 17:25