以下代码测试了stl 中 容器 list的简单使用方法,包括如何插入一条数据到list,遍历list, 删除一条数据等。
#pragma once #include "string" #include "list" #include "vector" #include "iostream" #include "algorithm" using namespace std; class CStudent { public: string name; int chinese; int math; public: void static inline printit(CStudent& stu) { cout << "name=" << stu.name << " "; cout << "math=" << stu.math << " "; cout << "chinese=" << stu.chinese; cout << endl; } bool operator<(CStudent &stu) const { if (name < stu.name) { return true; } else { return false; } } bool operator==(string studentname) const { if(name == studentname) { return true; } else { return false; } } }; typedef list<CStudent> STUDENT_LIST; class CExample { public: CExample(void); ~CExample(void); private: STUDENT_LIST m_list; public: void add(CStudent stu); bool remove(string name); bool findone(string name, CStudent *stu); void output(); void sort(); }; #include "StdAfx.h" #include "Example.h" CExample::CExample(void) { } CExample::~CExample(void) { } void CExample::sort() { m_list.sort(); } void CExample::add(CStudent stu) { m_list.push_back(stu); } void CExample::output() { for_each(m_list.begin(), m_list.end(), CStudent::printit); } bool CExample::remove(string name) { typedef STUDENT_LIST::iterator ITERATOR; ITERATOR LI; LI = find(m_list.begin(), m_list.end(), name); if (LI == m_list.end()) { return false; } else { m_list.erase(LI); return true; } } bool CExample::findone(string name, CStudent* stu) { typedef STUDENT_LIST::iterator ITERATOR; ITERATOR LI; LI = find(m_list.begin(), m_list.end(), name); if (LI == m_list.end()) { return false; } else { *stu = *LI; return true; } }
下边为主函数进行测试。
// stl.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Example.h"; #include "iomanip" int _tmain(int argc, _TCHAR* argv[]) { CExample example1; CExample example2; CStudent stu1[10]; for(int i=0; i<10; i++) { char name[100]; char buff[100]; sprintf(name, "%02d", 10-i); stu1[i].name = string(name); stu1[i].math = i * 5; stu1[i].chinese = i * 10; example1.add(stu1[i]); } example1.output(); example1.sort(); printf("*************************\n"); example1.output(); CStudent stu; bool ret = example1.findone("01", &stu); if (ret) { cout<<"find"<<endl; } else { cout<<"not find"<<endl; } system("pause"); return 0; }