Reputation: 1275
I have a struct as follows:
struct deviceDescription_t
{
std::string deviceID;
std::string deviceDescription;
};
I have defined a vector as follows:
std::vector<deviceDescription_t> deviceList
Let's say the vector deviceList
is made up of the following elements:
ID Description
=================
one_1 Device 1
two_2 Device 2
three_3 Device 3
....
I need to search through the ID field in deviceList
and get the description for this. Let's say I have one
as the predicate (search string). I now have to look through the ID field in the deviceList to find a match which I am doing by using
std::string temp = deviceID.substr(0, deviceID.find("_"));
but I am not sure how to use the find_if
mentioned in this question.
As one answer, it is advised to use
auto iter = std::find_if(deviceList.begin(), deviceList.end(),
[&](deviceDescription_t const & item) {return item.deviceID == temp;});
Using the above in my function, throws the following error
Local class, struct or union definitions are not allowed in a member function of a managed class.
Could anyone please guide me on how to use find_if to find the element matching the search criteria and return the description?
Upvotes: 3
Views: 1717
Reputation: 30418
Based on the error message, it sounds like you have a C++/CLI project.
When a lambda is used inline like you have in the call to find_if()
, it is really creating a small class for you that overrides operator ()
. Unfortunately the only way to call find_if()
from a managed class is to do that yourself:
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;
};
And then you would call find_if()
like this:
auto iter = std::find_if(deviceList.begin(), deviceList.end(),
DeviceFinder(temp));
Upvotes: 2