C++编程(E)

21 void assignin first in last firstlast void

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: cn 专门化的容器和迭代器 写容器上迭代的代码 int count(Itor<char>& ii, char term) { int c = 0; for(char* p = ii.first(); p; p=ii.next()) if(*p==term) c++; return c; } 注意,这种方式引起了一次虚函数的调用,很多情 况下,这种额外开销是无关大局的,但是,这种方 式对于标准库不合适 本例中:Itor甚至可以在Vector和List设计和实现 很久以后才提供 Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 16.2.2 有基类的容器 Simula采用如下风格定义了它的标准容器 struct Link{ Link* pre; Link* suc; }; class List{ Link* head; Link* curr; public: Link* get(); void put(Link*); }; // 一个List就是一个Link的 表,可以保存由Link派生的任 何类型的对象 class Ship:public Link{/*...*/}; void f(List* lst){ while(Link* po=lst->get()){ if(Ship* ps = dynamic_cast<Ship*>(po)){ //... } else { //... } } } Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 有基类的容器 常见情况是定义一个公共容器类型 class Container:public Object{ // 公共容器类型 public: virtual Object* get(); virtual void put(Object*); virtual Object*& operator(size_t); }; // 操作全部是虚的 class List:public Container{ public: Object* get(); void put(Object*); }; class Vector:public...
View Full Document

Ask a homework question - tutors are online