gpt4 book ai didi

c++ - 如何在对象 vector 中找到特定值

转载 作者:行者123 更新时间:2023-11-30 02:33:44 28 4
gpt4 key购买 nike

我有一个 Weapon 类的 vector ,然后循环并将 id 值添加到 vector 中。

Weapon* weapon;
vector<Weapon*> weaponVector;

for (int i = 0; i < 10; i++)
{
weapon = new Weapon(i);
weaponVector.push_back(weapon);
}

然后我有一个 vector 迭代器来尝试在 vector 中找到指定的数字。

vector<Weapon*>::iterator findIt;
findIt = find(weaponVector.begin(), weaponVector.end(), 5);

在 Weapon 类中,我创建了一个运算符重载来检查 id 是否相同。

bool Weapon::operator==(const Weapon& rhs)
{
return (rhs.id == id);
}

问题:

我试图在 weaponVector 中找到数字 5,但我一直收到此错误:

C2446 '==': no conversion from 'const int' to 'Weapon *

我尝试过的事情:

findIt = find(weaponVector.begin(), weaponVector.end(), Weapon(5));

Weapon five = Weapon(5);
findIt = find(weaponVector.begin(), weaponVector.end(), five);

无论我尝试什么,我都会不断出错。非常感谢任何帮助。

最佳答案

如果使用 C++11,只需使用带有 lambda 函数的 std::find_if:

#include <algorithm>
//...
int number_to_find = 5;
auto findIt = std::find_if(weaponVector.begin(), weaponVector.end(),
[&](Weapon* ptr) { return ptr->id == number_to_find;});

关于c++ - 如何在对象 vector 中找到特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35120960/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com