C/C++--set存储结构体

set所存储的内容需要可比较的,详细的内容见:http://en.cppreference.com/w/cpp/container/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 &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;
}


你可能感兴趣的:(struct,set,红黑树,compare,cc++)