我想从set中找到一个带有struct的partial成员的结构

时间:2014-11-14 01:30:49

标签: c++ struct stl

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依赖于info结构中的a和b(DB中的超级密钥类型)。 我想找到set的迭代器,它有结构成员a和b与p.first和second完全相同。并想要打印它 我必须将哪些代码放入(??)?

2 个答案:

答案 0 :(得分:0)

你可以这样做

第一种方式:

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

答案 1 :(得分:0)

如果要将结构存储在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!
}
相关问题