如何使用结构的向量数组?

时间:2018-09-29 12:16:53

标签: c++ arrays vector

所以我有这个结构:

struct foo{
    DWORD fooB;
    char *fooA;
}

并且我有一个变量DWORD bar;,那么如何确定bar是否与结构中的任何fooB相匹配?

编辑:我的代码(当前)

#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 个答案:

答案 0 :(得分:3)

您只需提供一个比较运算符即可将DWORDfoo进行比较:

#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
    }
}