BrandonW000
BrandonW000

Reputation: 31

How to change the default integer value in a map?

I am creating a map to compare and see if all letters of a word are unique or not. When I create this map I store the value of 1 for the corresponding character. Problem is, when I print the values of the map from the character keys I only receive zeros for all values.

While trying to research this, someone had told me this is due to all values of the map are defaulted to zero and my integer has to be initialized for it to change. I am not completely clear on what they meant by the integer needs to be initialized because I should be able to pass in a literal integer value, right?

The following is the code I currently have, as you will see I am trying to pass in 1 for the characters of the word and my code checks to see if the character already exists in the map:

    #include <iostream>
    #include <map>
    using namespace std;
    bool unique(char const* word)
      {
       map<char,int> cmpr;

       for(int i =0; word[i]!='\0';i++)
       {
         if(cmpr[word[i]])
         {
           cout<<"Not all unique";
           return false;
         }
    else
        {
             cmpr.insert(pair<char,int>(word[i],1));
        }
            cout<<cmpr[char(word[i])];
    }
    for(map<char,int>::iterator it = cmpr.begin(); it != cmpr.end();it++)
    {

        cout<<it->first<<" and "<<it->second<<endl;


    }
    return true;
}
int main()

{
    unique("hello");
}

And my output results in (when trying to print first and second values of map nodes):

    e and 0 
    h and 0
    l and 0
    o and 0

Upvotes: 1

Views: 82

Answers (2)

NathanOliver
NathanOliver

Reputation: 180650

The problem here is that

if(cmpr[word[i]])

Inserts a element into the map if one does not exist which it does not here. That means that

cmpr.insert(pair<char,int>(word[i],1));

Is a do nothing operation since the key word[i] already exists.

What you can do is change the condtion to

if(cmpr.find(word[i]) != cmpr.end())

since find will not insert an element or change

cmpr.insert(pair<char,int>(word[i],1));

to

cmpr[word[i]] = 1;

To get it to work


Do note though that none of this is really necessary. If you use a std::sting and a std::set then you entire function could be written as

bool unique(const std::string& word)
{
    return std::set(word.begin(), word.end()).size() == word.size();
}

What that does is constructs a set from the string and the set has the same mechanics were it only allows unique keys. This means that if the sizes are not the same then there was at least one repeated character in there.

Upvotes: 2

Pete Becker
Pete Becker

Reputation: 76315

You can use the default value with an increment:

if (cmpr[word[i]]++ != 0)
    // value was already present

This has the added bonus (depending on how you look at it) that you can get the number of occurrences of each character after the data has been added.

Upvotes: 0

Related Questions