STL-----list的反轉和排序

#include<iostream>
#include<algorithm>
#include<list>
#include<string>

using namespace std;

//list反轉和排序:

//list打印函數:
void printList(const list<int>&L)
{
	for (list<int>::const_iterator it = L.begin(); it != L.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;
}

//排序回調函數:
bool myCompare(int val1, int val2)
{
	return val1 > val2;
}

void test01()
{
	list<int> L;

	L.push_back(10);
	L.push_back(20);
	L.push_back(30);
	L.push_back(40);

	L.reverse();
	printList(L);

	//但是,所以不支持隨機訪問的迭代器,都不能使用系統提供的sort算法;
	//如果不支持系統提供的sort算法,那麼這個類內部會提供相應的sort算法;
	//例如:sort(L.begin(),L.end());不能通過編譯;

	L.sort();
	//從小到大排序;
	printList(L);

	//要從大到小,使用回調函數:
	//不能寫小括號,小括號是函數的調用:
	L.sort(myCompare);
	printList(L);
}

//自定義數據類型:
class Person
{
public:
	Person(string name ,int age):m_Name(name),m_Age(age){}
	string m_Name;
	int m_Age;
};

void printList_2(const list<Person>&l)
{
	for (list<Person>::const_iterator it = l.begin(); it != l.end(); it++) {
		cout << "名字是:"<<(*it).m_Name<<"    年齡是:" << (*it).m_Age << endl;
	}
}

//自定義類型的回調函數:
bool myCompare_2(Person &p1, Person & p2)
{
	if (p1.m_Age < p2.m_Age) {
		return true;
	}
	else
		return false;
}

void test02()
{
	list<Person> L1;

	Person p1("sadsad", 10);
	Person p2("asfaf", 20);
	Person p3("zxcasd", 40);
	Person p4("ertret", 50);
	Person p5("dfgdfg", 10);

	L1.push_back(p1);
	L1.push_back(p2);
	L1.push_back(p3);
	L1.push_back(p4);
	L1.push_back(p5);


	printList_2(L1);

	//按年齡進行排序:
	L1.sort(myCompare_2);
	cout << "按年齡進行排序:" << endl;
	printList_2(L1);

}

int main()
{
	test01();
	test02();
	system("pause");
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章