简体   繁体   English

如何修复C ++中的“哈希图错误:”错误

[英]How to fix “Hashmap error: ” error in C++

I want to use hashmap in C++ in Ubuntu 18.04. 我想在Ubuntu 18.04中的C ++中使用哈希图。 Butthis error makes me confusing. 但是这个错误使我感到困惑。

I want to use hashmap in C++ in Ubuntu 18.04. 我想在Ubuntu 18.04中的C ++中使用哈希图。 Butthis error makes me confusing. 但是这个错误使我感到困惑。

The complete error code is "Hashmap error: no matching function for call to 'std::map, int>::find(__gnu_cxx::__alloc_traits 完整的错误代码是“哈希图错误:没有匹配函数调用'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; }

I do not know what happened. 我不知道发生了什么。 Please someone helps me. 请有人帮助我。 ^~^ ^〜^

std::string::at returns a reference to a char , a single character. std::string::at返回对char (单个字符)的引用。 Meanwhile std::map::find expected a reference to the key type, a std::string . 同时, std::map::find需要对键类型std::string的引用。 There is no implicit conversion from a single character to a string. 没有从单个字符到字符串的隐式转换。 So you don't give find the argument it expected. 因此,您不会find期望的参数。

A possible workaround is to use std::basic_string::substr instead of at . 可能的解决方法是使用std::basic_string::substr而不是at This member function returns a string, by value, that holds a substring. 该成员函数按值返回一个包含子字符串的字符串。 You give it a position and how many characters to read. 您给它一个位置以及要读取的字符数。 So the immediate fix to your code can be: 因此,对代码的直接修复可以是:

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

Other than that, do note that std::map is an ordered map . 除此之外,请注意std::map是一个有序的map As such it is usually implement by using a self-balancing binary tree. 因此,通常通过使用自平衡二叉树来实现。 If you don't need order, and indeed want amortized constant lookup time like a hash would provide, you need std::unordered_map . 如果您不需要订单,并且确实希望像哈希一样提供摊销的固定查找时间,则需要std::unordered_map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM