遇到了一段代码,它定义并使用了类似于下面的typedef:
typedef char CHAR[10];
void fun(std::string s) {}
int main()
{
CHAR c;
fun(c);
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是,这是有效的.我的问题是为什么定义和使用这样的typedef以及它是如何工作的.在我看来,CHAR本身不应该起作用,它应该始终是CHAR [10].
此外,如果我更改fun声明以接受std :: string&而不是std :: string,则会抛出编译错误.我不知道为什么.
有人可以帮我理解这个吗?
我已经创建了一个char字符串的映射作为键,而int作为来自二维char数组的值.我看到地图中插入了重复的条目!
为了进一步测试,我向地图添加了两个相同值的char字符串(也在代码中,注释了),并且只添加了其中一个.
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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
ORIG
abc
1
pqr
2
xyz …Run Code Online (Sandbox Code Playgroud)