Haza
Haza

Reputation: 97

Find value on unordered_map

So in the beginning i had an unordered_map with an int as the key and string as the value initialized with 256 ASCII characters but later i found myself in the need to search for a string in the dictionnary but i couldnt use map::find since my key is an int . So here is my question how can i search for a specific value in an unordered map? or how should i modify this method to initialize all ASCII characters in a unordered_map where the key is a string and i could use map::find?

void InitDico (unordered_map<int,string>& Dico){
   Dico.clear();
   for (int i = 0; i < 256; ++i)
   {
       Dico[i] = (char)i;
   }}

What i tried :

void InitDico (unordered_map<string,int>& Dico){
   Dico.clear();
   for (int i = 0; i < 256; ++i)
   {
       Dico.insert({(char)i , i});  
   }}

Upvotes: 0

Views: 1041

Answers (2)

Caleth
Caleth

Reputation: 62636

std::string has a constructor that takes a count and a char, and constructs a string of count repetitions of that char.

It is implementation-defined whether a char object can hold negative values.

void InitDico2(std::unordered_map<std::string,int>& Dico) {
    Dico.clear();
    for (unsigned char c = 0; c < 256; c++)
    {
        Dico[{1, c}] = c;
    }    
}

Upvotes: 1

Haza
Haza

Reputation: 97

So tanks to super i did it , i've done a really dumb mistake.... so here is the code :

void InitDico2(unordered_map<string,int>& Dico) {
Dico.clear();
string s ="";
char c;
for (int i = 0; i < 256; i++)
{
    c = (char)i;
    s += c;
    Dico[s] = i;
    s.clear();

}}

Upvotes: 0

Related Questions