【问题标题】:How to fix "Hashmap error: " error in C++如何修复 C++ 中的“Hashmap 错误:”错误
【发布时间】:2019-01-02 08:48:07
【问题描述】:

我想在 Ubuntu 18.04 的 C++ 中使用 hashmap。但是这个错误让我很困惑。

我想在 Ubuntu 18.04 的 C++ 中使用 hashmap。但是这个错误让我很困惑。

完整的错误代码是“Hashmap error: no matching function for 调用‘std::map, int>::find(__gnu_cxx::__alloc_traits

::value_type&)"

#include <iostream>
#include <map> using namespace std;

int main() {
    string s = "dfsfsdfsf";
    int i = 0, j = 0, ans = 0, leng;
    map<string,int> window;
    leng = s.length();
    for(;j < leng; j++){
        if(window.find(s.at(j)) != window.end()){
            i = max(i, window[s.at(j)])
        }
    }
    return 0; }

我不知道发生了什么。请有人帮助我。 ^~^

【问题讨论】:

    标签: c++ c++11 hashmap


    【解决方案1】:

    std::string::at 返回一个对char 的引用,一个字符。同时std::map::find 期望引用密钥类型std::string。没有从单个字符到字符串的隐式转换。所以你不要给find它所期望的参数。

    一种可能的解决方法是使用std::basic_string::substr 而不是at。此成员函数按值返回一个包含子字符串的字符串。你给它一个位置和读多少个字符。因此,可以立即修复您的代码:

    window.find(s.substr(j,1)) != window.end()
    

    除此之外,请注意std::map 是一个有序映射。因此,它通常通过使用自平衡二叉树来实现。如果您不需要订单,并且确实希望像哈希一样提供分摊的常量查找时间,则需要std::unordered_map

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-08
      • 2021-07-18
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多