gpt4 book ai didi

c++ - 通过 id 并返回名称在 vector 中搜索结构元素

转载 作者:搜寻专家 更新时间:2023-10-31 02:15:09 24 4
gpt4 key购买 nike

我有一个结构如下:

struct deviceDescription_t
{
std::string deviceID;
std::string deviceDescription;
};

我定义了一个 vector 如下:

std::vector<deviceDescription_t> deviceList

假设 vector deviceList 由以下元素组成:

ID    Description
=================
one_1 Device 1
two_2 Device 2
three_3 Device 3
....

我需要搜索 deviceList 中的 ID 字段并获取对此的描述。假设我有 one 作为谓词(搜索字符串)。我现在必须查看 deviceList 中的 ID 字段以找到我正在使用

进行的匹配
std::string temp = deviceID.substr(0, deviceID.find("_"));

但我不确定如何使用 this 中提到的 find_if问题。

作为一个答案,建议使用

auto iter = std::find_if(deviceList.begin(), deviceList.end(),
[&](deviceDescription_t const & item) {return item.deviceID == temp;});

在我的函数中使用上面的代码,抛出以下错误

Local class, struct or union definitions are not allowed in a member function of a managed class.

谁能指导我如何使用 find_if 找到符合搜索条件的元素并返回描述?

最佳答案

根据错误消息,听起来您有一个 C++/CLI 项目。

当像调用 find_if() 那样内联使用 lambda 时,它实际上是在为您创建一个覆盖 operator () 的小类。不幸的是,从托管类调用 find_if() 的唯一方法是您自己调用:

struct DeviceFinder
{
public:
DeviceFinder(const std::wstring& temp)
: m_temp(temp)
{
}

bool operator() (const deviceDescription_t& item) const
{
return item.deviceID == m_temp;
}

private:
const std::wstring& m_temp;
};

然后你可以这样调用 find_if():

auto iter = std::find_if(deviceList.begin(), deviceList.end(),
DeviceFinder(temp));

关于c++ - 通过 id 并返回名称在 vector 中搜索结构元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39017388/

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