【问题标题】:How to work with a vector array of struct? [closed]如何使用结构的向量数组? [关闭]
【发布时间】:2018-09-30 03:58:02
【问题描述】:

所以我有这个结构:

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, 

【问题讨论】:

标签: c++ arrays vector


【解决方案1】:

您可以简单地提供一个比较运算符来比较DWORDs 和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
    }
}

【讨论】:

  • 嗨,谢谢。但是你在 C++ 中如何称呼bool operator==(DWORD lhs, foo const &amp;rhs)?因为它不是函数
  • 比较运算符。 learncpp.com/cpp-tutorial/…
  • 谢谢!如果您不介意最后一个问题,它是如何在代码中使用的?编辑:对不起,我没有看到链接,谢谢
  • std::find()使用。要自己使用它,好吧,定义它后,您也可以比较 DWORDs foos:例如。 if (42 == foo{ 42, nullptr }) // .,.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多