debug断言矢量迭代器不可用find_if删除
debug assert vector iterator not dereferncable with find_if
我想将我的循环转换为find_if lambda,但我总是会得到相同的结果向量迭代器,而不是删除。
void SearchObjectDescription(std::vector<std::string>& input, Player & player)
{
//--local variable
bool found = false;
//std::find_if
std::vector<std::string>::iterator i = std::find_if(input.begin(), input.end(),[&](Player player)
{
if ((player.InInventory((*i)) ) == true)
{
std::cout << (player.GetInventory().ItemByName((*i))).ExamineObject() << std::endl;
return true;
}
else
{
std::cout << "Object not in invetory!" << std::endl;
return false;
}
});
//original for loop
//for (std::vector<std::string>::iterator i = input.begin()+1; i != input.end(); i++)
//{
// if (player.InInventory((*i))== true)
// {
// std::cout << (player.GetInventory().ItemByName((*i))).ExamineObject() << std::endl;
// found = true;
// break;
// }
//}
//if (found ==false)
//{
// std::cout << "Object not in invetory!" << std::endl;
//}
}
有人可以帮我吗?
您错误地考虑了lambda。 std::find_if
函数是第三个参数,即获取向量元素的lambda,如果是您搜索的元素,则返回。
lambda的目的是拿一个元素,并确定它是否合适。
然而,您的lambda不会收到字符串向量的元素,而是将播放器作为参数。但是您显然没有玩家列表,您有字符串列表。为什么要检查的元素应该是Player
?
而是捕获播放器变量并接收要检查的元素。看起来像这样:
void SearchObjectDescription(std::vector<std::string>& input, Player & player)
{
auto i = std::find_if(input.begin(), input.end(),[&](const std::string& item)
{
// item is equal to the current element being checked
// player is captured by reference because of [&]
// if the item `item` is in inventory, return true.
return player.InInventory(item);
});
if (i != input.end()) {
// if it's not equal to the end, *i is the found item.
}
}
请注意,在C 14中,您可以在lambda中接收auto&&
,并将其推荐为string&
:
std::find_if(input.begin(), input.end(), [&](auto&& item)
{
// type of item is std::string&
// ...
});
您不能在lambda内部使用i
迭代器,因为直到std::find_if()
退出后才初始化它。您需要使用lambda的输入参数,该参数将是vector
的std::string
,而不是Player
对象。
另外,您没有检查std::find_if()
的返回值,以确保在取消给它之前具有有效的迭代器。
您没有正确地将for
循环转换为基于lambda的std::find_if()
。改用此方法:
void SearchObjectDescription(std::vector<std::string>& input, Player & player)
{
auto i = std::find_if(input.begin()+1, input.end(),
[&](const std::string &s) { return player.InInventory(s); });
if (i != input.end())
{
std::cout << (player.GetInventory().ItemByName(*i)).ExamineObject() << std::endl;
}
else
{
std::cout << "Object not in inventory!" << std::endl;
}
}
相关文章:
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- OpenMP卸载说'fatal error: could not find accel/nvptx-none/mkoffload'
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 为什么 SearchBack 中的 if (find == A[i]) 除了第一次之外没有给出 true?在调试时,除了第一次之外显然不起作用