【问题标题】:get value from std::map in c++ which has custom type从具有自定义类型的 c++ 中的 std::map 获取值
【发布时间】:2015-03-31 15:53:39
【问题描述】:

我已将地图初始化为:

typedef void*   ProxyClientHandler;
std::map<string,ProxyClientHandler> connectedClient;

我将值插入到这张地图中

ProxyClientHandler client;
string device;
connectedClient.insert ( std::pair<string,ProxyClientHandler>(device,client) );

到此为止没有错误返回。

但是当我要访问给定相关键的值时

string deviceId; 
ProxyClientHandler client = connectedClient.find(deviceId);

它给了我一个错误:

错误:无法将参数 '1' 的 'std::map, void*>::iterator {aka std::_Rb_tree_iterator, void*> >}' 转换为 'ProxyClientHandler {aka void*}' 到 'int DHProxyClientDelPort (ProxyClientHandler, int)'

我该如何解决这个问题???

【问题讨论】:

  • find 返回一个迭代器。你想要at[]

标签: c++ c++11


【解决方案1】:

std::map::find() 返回迭代器,通常你可以这样使用它:

auto it = map.find( key );
if( it == map.end() ) {
   // key not found
}
ProxyClientHandler client = it->second;

【讨论】:

    【解决方案2】:

    find 返回一个迭代器。

    std::map<string,ProxyClientHandler>::iterator it = connectedClient.find(deviceId);
    

    或者,如果您验证(或仅通过代码逻辑知道)带有键 deviceId 的元素在 map 内,则应使用 []

    ProxyClientHandler client = connectedClient[deviceId];
    

    【讨论】:

    • 恐怕在这种情况下使用operator[] 会不安全或无效或两者兼而有之。我不会推荐它。
    • @Slava 同意。 std::map::operator[] 的行为在他们设计它的时候可能看起来是个好主意,但它太愿意隐藏逻辑错误了。即使您 99.9% 确定密钥是安全的,myMap.at(key) 也同样简单,并且会定位错误而不是隐藏它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多