【问题标题】:Search for a struct element in vector by id and return name通过 id 搜索向量中的结构元素并返回名称
【发布时间】:2016-08-18 11:45:28
【问题描述】:

我有一个结构如下:

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

我已经定义了一个向量如下:

std::vector<deviceDescription_t> deviceList

假设向量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;});

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

托管类的成员函数中不允许本地类、结构或联合定义。

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

【问题讨论】:

标签: c++ vector struct


【解决方案1】:

根据错误消息,听起来您有一个 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));

【讨论】:

  • 在比较运算符中,您可以编写任何您想要的逻辑: bool operator() (const deviceDescription_t& item) { auto pos = item.deviceID.find("_")); if (pos == std::string::npos) 返回假;返回 item.deviceID.substr(0, pos) == m_temp; }
  • @Andy 我应该如何将 iter.deviceDescription 分配给一个字符串变量,比如 std::string temp = (*iter).description 会引发错误。
  • 错误:向量迭代器不可解引用
  • @smyslov 你确定find_if() 在向量中找到了一个项目吗?如果找不到项目,我只能重新创建。您可以通过比较 iterdeviceList.end() 来检查是否找到了设备。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-11
  • 2011-03-21
  • 1970-01-01
  • 2020-05-03
相关资源
最近更新 更多