如何在 C++11 中查找和更新向量中的一个嵌套结构

How to find and update one nested structure in a vector in C++11

本文关键字:嵌套 一个 结构 向量 C++11 查找 更新      更新时间:2023-10-16

我有一个需要查找结构是否存在包含嵌套结构的向量:

#include <iostream>
#include <algorithm>
#include <vector>
typedef struct Obj {
int id[128];
int len;
} ID;
typedef struct Details {
ID id;
int fwid;
int respfmt;
} IDDetails;
std::vector<IDDetails> details =
{
{ { { 2, 2, 1 }, 3 }, 0, 1 },
{ { { 2, 2, 2 }, 3 }, 0, 2 }
};
class A {
public:
int SetDetails(std::vector<IDDetails>& ids, ID &id)
{}
};
int main()
{
A a;
ID d = { { 2, 2, 1 }, 3 };
a.SetDetails(details, d);
return 0;
}

我在SetDetails中唯一的逻辑是遍历矢量,然后验证其详细信息,但是有没有更好的方法来精确匹配和更新矢量中的结构?

#include <cstring>
#include <algorithm>
// ...
bool operator==(ID const &lhs, ID const &rhs)
{
return lhs.len == rhs.len && std::memcmp(lhs.id, rhs.id, lhs.len) == 0;
}
// ...
auto f = std::find_if(ids.begin(), ids.end(), [&](IDDetails const &i) { return i.id == id; });