我想从具有结构部分成员的集合中找到一个结构
I want to find a struct from set with partial member of struct
struct info{
int a;
int b;
double c;
double d;
int e;
};
set<info> infoSet;
info information;
information.a = 1;
information.b = 1;
information.c = 1;
information.d = 1;
information.e = 1;
infoSet.insert(information);
information.a = 2;
information.b = 2;
information.c = 2;
information.d = 2;
information.e = 2;
infoSet.insert(information);
typedef pair<int, int> pairs;
pairs p;
p.first = 1; p.second = 1;
set<info>::iterator it;
it.find(??)
c,d 和 e 依赖于信息结构中的 a 和 b(DB 中的超级键)。我想找到具有与 p.first 和 second 完全相同的结构成员 a 和 b 的集合迭代器。并想打印它我必须输入哪个代码
你可以这样做
第一种方式:
set<info> infoSet
for_each(infoSet.begin(),infoSet.end(),bind2nd(ptr_fun(compare), pairs);
//compare fun
void compare(info, pair<int, int>)
{
..... you can compare them here
}
for_each就像"for(..)"一样,所以第二种方式是
set<info>::iterator it = infoSet.begin();
for(it; it!=infoSet.end(); it++)
{
if(it.first == p.first)
{
...// do what you want
break;
}
}
如果你想把
你的结构存储在一个set
中,你需要为它提供一个比较谓词。
我想你想让你的结构尽可能简单,所以我在你的结构之外做了谓词和一个转换函数。
示例如下:
struct Info
{
int a;
int b;
double c;
double d;
int e;
};
struct CompareInfo
{
bool operator() (const Info& lhs, const Info& rhs) const
{
return (lhs.a < rhs.a) && (lhs.b < rhs.b); // you can define your own rule here
}
};
typedef std::pair<int, int> Pairs;
Info MakeInfo(Pairs p) // convert from Pairs to Info
{
Info i = {p.first, p.second, 0, 0, 0}; // not sure what are values of c, d, e
return i;
}
std::set<Info, CompareInfo> infos;
Info info1 = {1,1,1,1,1};
infos.insert(info1);
Info info2 = {2,2,2,2,2};
infos.insert(info2);
Pairs p(1,1);
auto it = infos.find(MakeInfo(p));
if (it != infos.end())
{
// you found it!
}
相关文章:
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 静态结构和一个定义规则
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 如何在 C++11 中查找和更新向量中的一个嵌套结构
- 在学习数据结构之前对STL有一个了解是好的吗?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 使用完数据结构后清空数据结构是一个好习惯吗?
- 如何制作一个地图,其中的值是C++中的结构数组
- 如何将数据从一个结构链接到另一个结构
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- error dllimport 函数的定义不允许在一个特定的联合中,而其他类、结构和联合将按预期导出
- std::transform 将一个结构数组复制到另一个结构数组
- C++:如何做一个链表,结构作为参数传递?
- 输入 ctrl + x 后如何再次 cin (cin<<x) 循环(cin 一个结构)
- 两个附带的类层次结构-一个好的设计模式