考虑一个简单的 std::map<std::string*,std::string*>
,我想检查映射中是否存在字符串指针的值。
我试过了,但是当我想检查指向的(实际)值时,编译器会在映射中查找指针本身。
int main() {
map<string*,string*> c;
std::string a("dude");
std::string* b=new string("dude");
std::string* ap;
c.insert(std::make_pair<string*,string*>(&a,&a));
for( map<string*, string*>::iterator ii=c.begin(); ii!=c.end(); ++ii){
ap=(*ii).first;
if(ap->compare(*b)){
cout<<"Yeah, dude has been found\n";
}
}
if(c.find(b)==c.end()){
cout<<"No dude!\n";//wrong!
}
if(c.count(b)==0){//how to find out if there is dude string?
cout<<"No dude dude!\n";//wrong!
}else{
cout<<"Yeah, dude has been found\n";
}
return 0;
}
一般来说,我有两个字符串指针,我想比较这两个字符串。我该怎么做?
提前致谢。
最佳答案
您不能真正将指针用作键,除非您确实希望指针 成为键而不是它指向的内容。
指针&a
和指针b
不一样,所以找不到 key 。
改为使用普通(非指针)std::string
作为键,它应该工作得更好。
关于c++ - 如何确定 map 中是否存在字符串键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23187852/