C/C++--set存储自定义结构体

来源:互联网 发布:淘宝联盟怎么用 编辑:程序博客网 时间:2024/05/14 13:26

set存储结构体,结构体必须重载<运算符


代码如下:

// Test.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include <set>#include <string>#include <sstream>using namespace std;struct A{int age;string name;bool operator<(const A &b) const{return age < b.age;}};// bool operator<(const A &a, const A &b)// {// return a.age < b.age;// }int _tmain(int argc, _TCHAR* argv[]){set<A> setA;stringstream ss;for (int i = 0; i < 10; i++){ss.clear();ss.str("");ss << "test" << i;A a;a.age = i;a.name = ss.str();setA.insert(a);}for (set<A>::iterator it = setA.begin(); it != setA.end(); it++){A a = (A)(*it);printf("age = %d, name = %s \n", a.age, a.name.c_str());}getchar();return 0;}


0 0
原创粉丝点击