如下,
struct Club
{
string m_str;
int m_i;
Club(const string &s, int i)
{
m_str = s;
m_i = i;
}
};
vector vClub;
Club a("randylin",2);
Club b("forrest",1);
vector vClub;
vClub.push_back(a);
vClub.push_back(b);
在vClub中精确查找
m_str == "randy",m_i == 2
或者查找
m_str == "randy",取m_i
有两种方法:
(1)find
(2)find_if
下面是示例代码
//find_if方法
//自定义函数对象(谓词)
class Club_eq
{
public:
Club_eq(const string& ss):s(ss){}
bool operator() (const Club& c) const
{
return c.m_str == s;
}
private:
string s;
};
int main()
{
Club a("randylin",2);
Club b("forrest",1);
vector vClub;
vClub.push_back(a);
vClub.push_back(b);
vector::iterator iter;
iter = find_if(vClub.begin(), vClub.end(), Club_eq("randylin"));
if(iter != vClub.end())
{
cout << iter->m_i << endl;
}
return 1;
}
//find方法
//在结结构体重载operator==操作符
struct Club
{
string m_str;
int m_i;
Club(const string &s, int i)
{
m_str = s;
m_i = i;
}
bool operator==(const Club& c) const
{
return c.m_str == m_str && c.m_i == m_i;//这里可以自定匹配个数
}
};
int main()
{
Club a("randylin",2);
Club b("forrest",1);
vector vClub;
vClub.push_back(a);
vClub.push_back(b);
vector::iterator iter;
Club tmp("randylin",2);
iter = find(vClub.begin(), vClub.end(), tmp);
if(iter != vClub.end())
{
cout << iter->m_i << endl;
}
return 1;
}
阅读(8837) | 评论(0) | 转发(1) |