Why does my map print out zeros instead of ones for its values? I am trying to s
ID: 3781568 • Letter: W
Question
Why does my map print out zeros instead of ones for its values? I am trying to set an initial value of 1 for all of the characters from the word to the map. When I print out the first and second values of the map nodes I get all zeros for the values for each following character key. The basis of this problem is to find all unique characters of a word. The following is my code
#include <iostream>
#include <map>
using namespace std;
bool unique(char const* word)
{
map<char,int> cmpr;
for(int i =0; word[i]!='';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 :
e and 0
h and 0
l and 0
o and 0
Explanation / Answer
Analysis:
The default value for an integer is 0 and this concept is getting followed in line “cmpr.insert(pair<char,int>(word[i],p));”
I have taken the variable p which is copying the value to int but this is not happening because the integer is not initialized anywhere and by default is taking the value as 0.
Hence just update the program in cout as “cout<<it->first<<" and "<<it->second+1<<endl;”
The correct program is as follows:
#include <iostream>
#include <map>
using namespace std;
bool unique(char const* word)
{
map<char,int> cmpr;
for(int i =0; word[i]!='';i++)
{
if(cmpr[word[i]])
{
cout<<"Not all unique";
return false;
}
else
{
int p=3;
cmpr.insert(pair<char,int>(word[i],p));
}
//cout<<cmpr[char(word[i])];
}
for(map<char,int>::iterator it = cmpr.begin(); it != cmpr.end();it++)
{
cout<<it->first<<" and "<<it->second+1<<endl;
}
return true;
}
int main()
{
unique("hello");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.