0

So I have this struct:

struct foo{
    DWORD fooB;
    char *fooA;
}

and I have a variable DWORD bar;, so how do I find if bar matches any fooB in my struct?

EDIT: my Code (currently)

#include <algorithm> // for.   std::find

using namesapce std;

struct foo{
    DWORD fooB;
    char *fooA;
    // .... Use this
}

vector <DWORD> foo;


if ( std::find(vector.begin(), 
    vector.end(), pIdToFind) != 
    vector.end() )
    // We found the item in the list, so let's just continue 
else
// We haven't found it, 

1 Answers1

3

You could simply provide a comparison operator for comparing DWORDs to foos:

#include <vector>
#include <algorithm>

#include <windows.h>

struct foo {
    DWORD fooB;
    char *fooA;
};

bool operator==(DWORD lhs, foo const &rhs)
{
    return lhs == rhs.fooB;
}

int main()
{
    foo needle{ 42, nullptr };
    vector<DWORD> haystack;

    if (std::find(haystack.begin(), haystack.end(), needle) != haystack.end())
    {
        // We found the item in the list, so let's just continue 
    }
    else
    {
        // not found
    }
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • Hi, thanks. But what do you call the `bool operator==(DWORD lhs, foo const &rhs)` in C++? since it's not a function – jordan cedrick Sep 29 '18 at 12:48
  • comparison operator. https://www.learncpp.com/cpp-tutorial/96-overloading-the-comparison-operators/ – drescherjm Sep 29 '18 at 12:49
  • thanks! if you wouldn't mind one last question, how is it used in the code? EDIT: I havn't saw the link sorry, thanks – jordan cedrick Sep 29 '18 at 12:50
  • It *is* used by `std::find()`. To use it yourself, well, with it defined you can compare `DWORD`s too `foo`s: eg. `if (42 == foo{ 42, nullptr }) // .,. ` – Swordfish Sep 29 '18 at 12:53