Can someone please help me understand this?
I have created a map of char strings as key and int as a value from a two dimensional char array. I see duplicate entries being inserted in the map!
To test further, I added two char strings of the same value to a map (also in the code, commented), and only one of them was added.
void countstr(char words[][NUM_OF_STR])
{
map<char*, int> mwords;
cout<<"ORIG"<<endl;
for(int i = 0; i < NUM_OF_STR; i ++)
{
cout<<words[i]<<endl;
mwords.insert(pair<char*, int>(words[i], 0));
cout<<mwords.size()<<endl;
}
map<char*, int>::iterator itr;
cout<<endl<<"MAP"<<endl;
for(auto i = mwords.begin(); i != mwords.end(); i ++)
{
cout<<i->first<<"\t"<<i->second<<endl;
}
return;
}
int main()
{
char words[NUM_OF_STR][5] = { "abc", "pqr", "xyz", "abc", "pqr" };
/*map<char*, int> mwords;
mwords.insert(pair<char*, int>("abc", 1));
cout<<mwords.size()<<endl;
mwords.insert(pair<char*, int>("abc", 2));
cout<<mwords.size()<<endl;*/
countstr(words);
return 0;
}
Output:
ORIG
abc
1
pqr
2
xyz
3
abc
4
pqr
5
MAP
abc 0
pqr 0
xyz 0
abc 0
pqr 0
答案 0 :(得分:5)
如果比较comentario
和-verbose
,您会发现它们并不相同。那是因为它们是指针,所以运算符class ABC:
def __init__(self,debugFlag):
self.debugFlag = False
def some_function():
if self.debugFlag is True:
print "Some debug logs"
def set_flag():
self.debugFlag = True
,words[0]
等将查看您C字符串的地址,而不是内容。
由于它们的内容相同,所以it is possible — but not guaranteed — that their addresses will be the same too(这是字符串文字的事实)。在您的情况下,它们是不相同的,因此键在逻辑上是不同的,并且两个元素都被接受。
指针不是容器。
您可以通过提供自定义比较器来make the map use strcmp
instead,也可以只将words[3]
(或==
)用作密钥。 :)