c++ - 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.
}
请注意,这是一个简化版本,但我认为它明白了这一点。有什么建议么?编辑:在尝试简化代码时出现了一些语法错误。修复它们。
解决方案
As
是 a const std::vector<A*>
,其中不包含任何std::find_if(...)
元素,因此在这种情况下取消引用返回的迭代器是Undefined Behavior。
由于您没有提及您为什么在 中做任何事情As.end() - 1
,std::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;
}
推荐阅读
- apache - 如何在 Apache Directory Studio 中查看索引?
- java - 从 Google App Engine 请求标头获取时区偏移量?
- python - 如何在 anaconda 中安装 pyxdg?
- c# - 如何递归使用 LINQ WHERE?
- swift - Swift 属性观察器 - didset 与 willset 使用示例
- javascript - vue.js 变量不适用于 Node.js :
- mongodb - 查找所有重叠区间的计数
- oracle11g - 从 oracle11g 自动下载 csv 文件
- javascript - 引用数组时避免使用幻数
- c# - ASP.NET Core 2.0 IAuthorizationService 和过期的承载令牌