// listTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <list> using namespace std; /* 对元素的要求: 1.拷贝构造函数 2.赋值运算 3.构造函数 4.<运算(sort会用到) 5.析构函数 */ class TestEle { public: TestEle(int nCnt, const char* szName) : m_nCnt(nCnt) { strncpy(m_szName, szName, 64); } TestEle(const TestEle& oth) { this->m_nCnt = oth.m_nCnt; strncpy(this->m_szName, oth.m_szName, 64); } TestEle& operator=(const TestEle& oth) { this->m_nCnt = oth.m_nCnt; strncpy(this->m_szName, oth.m_szName, 64); return *this; } /* sort 使用*/ bool operator<(const TestEle& oth) { return (this->m_nCnt < oth.m_nCnt); } /* remove unique 使用 */ bool operator==(const TestEle& oth) { if (this->m_nCnt == oth.m_nCnt) { return true; } return false; } int GetCnt(void) const { return m_nCnt; } private: int m_nCnt; char m_szName[64]; }; bool MyComFun(const TestEle& oth1, const TestEle& oth2); bool MyComFun(const TestEle& oth1, const TestEle& oth2) { return (oth1.GetCnt() > oth2.GetCnt()); } int _tmain(int argc, _TCHAR* argv[]) { /* 构造函数 */ list<TestEle> list1; list<TestEle> list2(100, TestEle(101, "liyong")); list<TestEle> list3(list2.begin(), list2.end()); list<TestEle> list4(list2); /* 整个容器赋值 */ list<TestEle> list5; list5 = list2; /* 几个重要的成员函数用法 */ list4.resize(200, TestEle(333, "123456")); list4.resize(150, TestEle(444, "654321")); list4.assign(1000, TestEle(666, "abcdef")); list4.assign(list2.begin(), list2.end()); list4.insert(list4.begin(), TestEle(911, "help")); list4.insert(list4.begin(), 101, TestEle(9119, "hello")); list4.insert(list4.begin(), list2.begin(), list2.end()); list2.erase(list2.begin()); list4.erase(list4.begin(), list4.end()); list1.swap(list2); /* Operations */ list<TestEle> list6; list<TestEle> list8(11, TestEle(6666, "0000")); list<TestEle> list7(100, TestEle(777, "123456")); /* 剪接 */ list6.splice(list6.begin(), list7); list8.splice(list8.begin(), list7); list8.remove(TestEle(6666, "0000")); class CFunObj { public: bool operator()(const TestEle& oth) { if (777 == oth.GetCnt()) { return true; } return false; } }; list6.remove_if(CFunObj()); list<TestEle> list9; list9.push_back(TestEle(4, "cc")); list9.push_back(TestEle(4, "cc")); list9.push_back(TestEle(3, "cc")); list9.push_back(TestEle(5, "cc")); list9.push_back(TestEle(4, "cc")); list9.push_back(TestEle(4, "cc")); list9.unique(); list9.sort(); // merge list<TestEle> list10; list10.push_back(TestEle(5, "a")); list10.push_back(TestEle(4, "a")); list10.push_back(TestEle(3, "a")); list10.push_back(TestEle(2, "a")); list10.push_back(TestEle(1, "a")); //list10.sort(); list10.sort(MyComFun); list<TestEle> list11; list11.push_back(TestEle(11, "b")); list11.push_back(TestEle(10, "b")); list11.push_back(TestEle(9, "b")); list11.push_back(TestEle(8, "b")); list11.push_back(TestEle(7, "b")); //list11.sort(); list11.sort(MyComFun); //要求merge前调用sort,也就是要保持list有序, 并且merge和sort一致 //list10.merge(list11); list10.merge(list11, MyComFun); return 0; }