不确定修复“没有匹配的调用函数”错误

问题描述

我无法找出我遇到的错误

基本上,我有一个 const _history = window.history window.history = new Proxy(_history,{ get(target,key) { if (['pushState','replaceState','back','forward'].includes(key)) { return () => { window.dispatchEvent(new CustomEvent('routechange')) return target[key] } } return target[key] } }) ,它将 unordered_map 映射到 string,我正在尝试使用 int 返回 string

这是我写的:

int

其中 // for each int representations of neighbor nodes for(long unsigned int i = 0; i < labels.size(); i++) { // return string representation of neighbor nodes std::unordered_map<std::string,int>::const_iterator got = umap.find(labels[i]); ret.push_back(got->first); } 是字符串的 retvector 是整数的 labels,而 vector 是我的 umap。>

我得到的错误是这样的:

没有匹配的函数调用'std::unordered_map<:__cxx11::basic_string>,int>::find(__gnu_cxx::__alloc_traits<:allocator int>::value_type&)'

解决方法

您正在反向使用 unordered_map

您的 unordered_map 使用 std::string 作为其 key_type,而 int 作为其 mapped_type。这意味着它是按字符串索引条目,而不是整数。

因此,unordered_map::find() 接受 std::string 进行搜索,但您传入的是 int,因此出现错误。您正在尝试通过其映射值查找条目,但这不是 find() 的工作方式。它改为按其键搜索条目。

unordered_map 中搜索给定映射值的键的唯一方法是手动迭代条目。您可以为此使用 std::find_if(),例如:

// for each int representations of neighbor nodes
for(size_t i = 0; i < labels.size(); i++) {
    // return string representation of neighbor nodes
    int value = labels[i];
    auto got = std::find_if(umap.begin(),umap.end(),[=](const auto &elem){ return elem.second == value; }
    );
    if (got != umap.end())
        ret.push_back(got->first);
}

否则,如果您想通过 find() std::string int,您需要使用 unordered_map<int,string> 而不是 unordered_map<string,int>