首页 > 解决方案 > C++ find_if 导致绑定函数崩溃

问题描述

情况有点复杂,但我会尽力解释它。
我正在尝试从对象指针向量中获取指向对象的指针,其中对象的属性之一与变量字符串匹配。为此,我将字符串变量绑定到一个函数,然后使用绑定函数尝试找到该对象指针。但是,每当我尝试此操作时,它都会崩溃。我已经尝试了一堆不同的测试来找到问题,但我仍然一无所知。以下是相关代码:

class A {
std::string n;
...
public:
const std::string getN() {
return n
}
};
static bool checkN(std::string n1, A* a) {
        if (a->getN() == n1) {
            return true;
        }
        else {
            return false;
        }
    }
void function() {
using namespace std::placeholders;
A* a;
std::string compare = "Yes";
const std::vector<A*> As; //As[0].n = "Yes";
auto check = std::bind(checkN, compare, _1);
a = (*std::find_if(As.begin(), As.end() - 1, check));  //This is the line where it crashes.
}

请注意,这是一个简化版本,但我认为它明白了这一点。有什么建议么?编辑:在尝试简化代码时出现了一些语法错误。修复它们。

标签: c++algorithmvectorc++17bind

解决方案


As是 a const std::vector<A*>,其中不包含任何std::find_if(...)元素,因此在这种情况下取​​消引用返回的迭代器是Undefined Behavior

由于您没有提及您为什么在 中做任何事情As.end() - 1std::find_if(...)我会假设您这样做是为了摆脱分段错误,但恐怕也不会摆脱上述问题。

现在,要防止发生这种未定义的行为,您需要的是检查返回的迭代器是否没有超过容器的最后一个元素(即检查是否并且只有在那时才应该尝试取消引用返回的迭代器由.std::find_if(...)std::find_if(...) != As.end()std::find_if(...)

#include <functional>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <iomanip>
#include <vector>
#include <string>

// ...

int main() {
    using namespace std::placeholders;

    std::string compare = "Yes";

    const std::vector<A*> As;

    // Store the iterator returned by 'std::find_if(...)' inside a variable
    auto it = std::find_if(As.begin(), As.end(), std::bind(checkN, compare, _1));

    // Check whether the iterator is NOT past the last element i.e. check if it is not equals 'As.end()'
    if (it != As.end())
        std::cout << std::quoted(compare) << " found at index " << std::distance(As.begin(), it) << "!" << std::endl;
    // Otherwise, if the iterator is, in fact, equals 'As.end()', then it is safe to assume that the element was not found
    else
        std::cout << std::quoted(compare) << " was not found." << std::endl;
}

推荐阅读