Ваша строка не любая строка, а путь, если соответствующие файлы / каталог всегда существуют, вы можете использовать их номер узла (поле d_ino
в struct dirent
)
Примечание: dirent доступно в Linux / Unix / Windows, если у вас его нет из-за используемого компилятора, посмотрите Список всех файлов внутри папки и ее подпапок в Windows
Если файл / dir может не существовать, вы можете создать строку словаря -> int самостоятельно, пример:
#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;
}
Компиляция и выполнение:
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 $
Примечания:
Я не проверяю, все ли возможные значения unsigned int уже используются при вводе новой строки, у вас будут проблемы с памятьюдо этого случая, или используйте 64b без знака, чтобы быть уверенным; -)
идентификатор строки, безусловно, уникален, но зависит от исторического, хеш не зависит от исторического, нонесколько строк могут иметь одинаковый хеш