我有一个结构如下:
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查找符合搜索条件的元素并返回说明吗?
答案 0 :(得分:1)
根据错误消息,听起来你有一个C ++ / CLI项目。
当一个lambda像你在find_if()
的调用中一样被内联使用时,它实际上是为你创建一个覆盖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));