c++ - 如何确定 map 中是否存在字符串键?

标签 c++ c++11

考虑一个简单的 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/

相关文章:

c++ - 不同命名空间中别名声明的成员特化

c++ - STL Map<string, > 与 LLVM 库冲突

c++ - 如何在 C++ 中使用类型名?

c++ - MD5 散列时填充字符串

c++ - MacOS 的 "-std=gnu++0x"选项

c++ - 无法将套接字对象移动到 std::vector

c++ - 我需要将对象 vector 或括号括起来的列表传递给构造函数的选项

c++ - 字符串常量之前的预期标识符

c++ - 只允许将一个文件重定向到标准输入

C++11模板解析错误,使用模板别名进行类型推导