c++ - 取消引用 std::find_if 的结果时内存访问错误

标签 c++ debugging

<分区>

bool hasId(string id, vector<User>& map)
{
    User ans = *(find_if(map.begin(), map.end(), [&](User d)
    {   return (id==(d).uid());}));
    return ans.uid() == id;
}

最佳答案

如果未找到匹配项,则 find_if 返回 last(),在您的情况下为 map.end()end() 不返回有效的迭代器(它是最后一个元素之后的迭代器),但您假设始终找到匹配项并继续无条件地取消引用返回值。这是个问题。

您需要在取消引用之前执行检查。如果没有检查,您的函数只是假设总是找到匹配项,因为 ans.uid() == idfind_if 的谓词(因此是多余的),因此您可以也只需用 return true; 替换整个内容 :)

bool hasId(string id, vector<User>& map)
{
    return map.end() != find_if(map.begin(), map.end(), [&](User d)
    {   
        return id == d.uid();
    });   
}

顺便说一句,将 vector 称为 map 有点奇怪,至少会造成混淆。


Documentation for find_if

相关位:

template< class InputIt, class UnaryPredicate >
InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );

Return value

Iterator to the first element satisfying the condition or last if no such element is found.

关于c++ - 取消引用 std::find_if 的结果时内存访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13169396/

相关文章:

c++ - 如何在 Eclipse 中使用 MinGW 编译 boost 线程?

c++ - 内存中的视觉模式?

c# - 如何在没有 pdb 的情况下在堆栈跟踪中包含行号?

c# - VS 2017即时窗口显示 "Internal error in the C# compiler"

C++ 获取 linux 发行版名称\版本

c++ - 如何在C++中使用删除运算符删除单个数据

c++ - 在 C++ 中使用两个类层次结构实现双重分派(dispatch)

java - 车辆 2 车辆通信问题

PHP - 调试要求

macos - 链接时调试符号丢失?