Your string are not any string but path, if the corresponding files/dir always exist you can use their node number (field d_ino
in struct dirent
)
Note : dirent is available on Linux/Unix/Windows, if you do not have it because of the compiler you use look at List of all files inside the folder and its subfolders in Windows
If the file/dir may not exist you can make a dictionary string -> int by yourself, example :
#include <iostream>
#include <string>
#include <map>
#include <list>
class UI {
public:
UI() : next(1) {}
unsigned search(std::string) const;
unsigned get(std::string);
unsigned forget(std::string);
private:
std::map<std::string, unsigned> m;
std::list<unsigned> free;
unsigned next;
};
unsigned UI::search(std::string s) const {
std::map<std::string, unsigned>::const_iterator it = m.find(s);
return (it == m.end()) ? 0 : it->second;
}
unsigned UI::get(std::string s) {
std::map<std::string, unsigned>::const_iterator it = m.find(s);
if (it != m.end())
return it->second;
unsigned r;
if (!free.empty()) {
r = free.front();
free.pop_front();
}
else
r = next++;
m[s] = r;
return r;
}
unsigned UI::forget(std::string s) {
std::map<std::string, unsigned>::const_iterator it = m.find(s);
if (it == m.end())
return 0;
unsigned r = it->second;
m.erase(it);
if (r == (next - 1))
next -= 1;
else
free.push_back(r);
return r;
}
int main(void)
{
UI ui;
std::cout << "aze " << ui.search("aze") << std::endl;
std::cout << "aze " << ui.get("aze") << std::endl;
std::cout << "qsd " << ui.get("qsd") << std::endl;
ui.forget("aze");
std::cout << "aze " << ui.search("aze") << std::endl;
std::cout << "wxc " << ui.get("wxc") << std::endl;
return 0;
}
Compilation and execution :
pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra c.cc
pi@raspberrypi:/tmp $ ./a.out
aze 0
aze 1
qsd 2
aze 0
wxc 1
pi@raspberrypi:/tmp $
Notes :
I do not check if all the possible values of an unsigned int are already used when you enter a new string, you will have problem of memory before that case, or use a 64b unsigned to be sure ;-)
the ID of a string is certainly unique but depends on the historic, a hash do not depends on an historic but several strings may have the same hash