2014-11-14 49 views
0
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的集合的迭代器。並想打印它 哪些代碼必須放入(??)?我想從結構中找到一個結構體struct

+0

哪裏是'info',可以存儲它在一個'set'的比較操作? –

回答

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就像是 「爲(..)」,所以第二個方法是

set<info>::iterator it = infoSet.begin(); 
for(it; it!=infoSet.end(); it++) 
{ 
    if(it.first == p.first) 
{ 
    ...// do what you want 
    break; 
} 
} 
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! 
} 
+0

謝謝!它適用於我! –

+0

太棒了!恭喜! ;) –

相關問題