STL 之 Set容器 修改容器中的元素
class person{public: int age; std::string name; person(int a, std::string s):age(a),name(s){ } person(const person& info) { age = info.age; nam...
class person{
public:
int age;
std::string name;
person(int a, std::string s):age(a),name(s){
}
person(const person& info)
{
age = info.age;
name = info.name;
}
person& operator =(const person&)
{
return *this;
}
bool operator<(const person& src) const{ //要想set中使用自定义类,必须手动实现<函数
return age < src.age;
}
};
std::set<person> ps;
person& getperson(int agess)
{
for (std::set<person>::iterator it = ps.begin(); it != ps.end(); it++)
{
if (it->age == agess)
return const_cast<person&>(*it); //返回迭代器值 的引用
}
}
//测试
int _tmain(int argc, _TCHAR* argv[])
{
ps.insert(person(12,"abc"));
ps.insert(person( 33, "qwe" ));
ps.insert(person( 56, "tgb" ));
for (std::set<person>::iterator it = ps.begin(); it != ps.end(); it++)
{
std::cout << it->age << " " << it->name << std::endl;
}
person& pp=getperson(33);
pp.name = "hello";
for (std::set<person>::iterator it = ps.begin(); it != ps.end(); it++)
{
std::cout << it->age << " " << it->name << std::endl;
}
getchar();
return 0;
}
更多推荐
所有评论(0)