如何判断字符串键是否存在于映射中

How to figure out if the string key exists in a map?

本文关键字:于映射 存在 映射 是否 字符串 何判断 判断      更新时间:2023-10-16

考虑到一个简单的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 foundn";
        }
    }
    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 foundn";
    }
    return 0;
}

一般来说,我有两个字符串指针,我想比较这些字符串。我该怎么做
提前谢谢。

你不能真正使用指针作为键,除非你真的希望指针是键,而不是它指向的。

指针&a和指针b不同,这就是为什么找不到键的原因。

使用普通(非指针)std::string作为键,它应该会更好地工作。

如果经过仔细测量和考虑,您仍然确定不能接受复制std::string s,并且可以保证string s与地图一样长,请考虑以下方法。不要仅仅因为使用它们。

最简单的方法就是使用std::reference_wrapper<T>。它与原始指针具有相同的语义,只是对引用的对象执行比较/哈希等操作
Chnossos刚刚提到了那个有用的标准库成员。

在这一点之后留下我以前的答案,因为它们允许更多的定制。

添加您自己的struct wrapped_pointer{std::string* x},并专门设计比较器std::less来考虑指向字符串。

通过为std::map的第三个模板自变量提供显式自变量,可以实现大致相同的结果。

如果您提供一个自定义函数/函子来比较两个string*s,您可以随心所欲。

这是一个如你所想的那样有效的版本:

#include <map>
#include <iostream>
#include <string>
using namespace std;
// Define a functor class to compare two string* objects.
struct string_less
{
   bool operator()(string* lhs, string* rhs) const
   {
      return (lhs->compare(*rhs) < 0);
   }
};
int main() {
    // Use string_less while constructing the map.
    map<string*,string*, string_less> 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*, string_less>::iterator ii=c.begin(); ii!=c.end(); ++ii){
        ap=(*ii).first;
        // This was another line that needed to be fixed.
        if(ap->compare(*b) == 0 ){
            cout<<"Yeah, dude has been foundn";
        }
    }
    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 foundn";
    }
    return 0;
}

在我的机器上运行程序的输出:

是的,伙计被找到了是的,伙计被找到了