C++编程(F)

Educn 1721 vector vector vector at vector beijing

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: p(平 衡树)、string(11章所描述的方式或者数组) Beijing University of Posts & Telecommunications Beijing [email protected] 17.1.4 对元素的要求 容器里的元素是被插入对象的副本 一个对象要想成为容器的元素,它就必须属 于某个允许容器的实现对他进行复制的类型 容器可以利用复制构造函数或者赋值做元素 的赋值工作,在两种情况下,都要求复制结 果是一个等价的对象 Beijing University of Posts & Telecommunications Beijing [email protected] 17.1.4.1 比较 关联容器要求其元素是有序的,许多可以应 用于容器的操作也是这样(例如,sort()) 按照默认方式,这个序由<运算符定义,如 果<不合适,程序员必须另外提供合适的比 较操作 排序准则必须定义一种严格的弱顺序(strict weak ordering),即小于和等于操作必须 具有传递性 Beijing University of Posts & Telecommunications Beijing [email protected] 比较示例 template<class Ran> void sort(Ran first, Ran last); template<class Ran, class Cmp> void sort(Ran first, Ran last, Cmp cmp); class Nocase{ public: bool operator()(const string&, const string&) const; }; bool Nocase::operator()(const string& x, const string& y) const{ string::const_iterator p = x.begin(); string::const_iterator q = y.begin(); while(p!=x.end() && q != y.end() && toupper(*p)==toupper(*q)){ ++p; ++q; } if(p == x.end() ) return q!=y.end(); if(q == y.end() ) return false; return toupper(*p) < toupper(*q); } Beijing University of Posts & Telecommunications Beijing [email protected] 比较示例 使用上面的比较准则调用sort(),例如,给 定fruit: apple pear Apple Pear lemon 用sort(fruit.begin(), fruit.end(), Nocase())将产生 fruit: Apple apple lemon Pear pear 而简单的用sort(fruit.begin(), fruit.end())将给出 fruit: Apple Pear apple lemon pear Beijing University of Posts & Telecommunications Beijing [email protected] 17.1.4.2 其他关系运算符 按默认规定,容器和算法在需要小于比较时 都采用<,如果默认方式不何时,程序员必 须另行提供一个比较准则 标准库在名字空间std::rel_ops里定义了各 种比较运算符,并通过<utility>给出 template<class T>bool rel_ops::operator!=(const T& x, const T& y) {return !(x==y);} template<class T>bool rel_ops::operator>(const T& x, const T& y) {return y<x;} template<class T>bool rel_ops::operator<=(const T& x, const T& y) {return !(y<x);} template<class T>bool rel_ops::operator>=(const T& x, const T& y) {return !(x<y);} // 注意以上运算符都是定义在<运算符基础之上的 Beij...
View Full Document

This note was uploaded on 02/10/2014 for the course ECE C++ taught by Professor Xiaoshengtang during the Fall '13 term at BUPT.

Ask a homework question - tutors are online