文章目录:
4.1 顺序容器
4.1.1 vector和deque
1)示例1:
#include <iostream>
#include <vector>
using namespace std;
template<class T>
void PrintVector( T s, T e){
for(; s != e; ++s)
cout << * s << " ";
cout << endl;
}
int main() {
int a[5] = { 1,2,3,4,5 };
vector<int> v(a,a+5); //将数组a的内容放入v
cout << "1) " << v.end() - v.begin() << endl;
//两个随机迭代器可以相减,输出 1) 5
cout << "2) "; PrintVector(v.begin(),v.end());
//2) 1 2 3 4 5
v.insert(v.begin() + 2, 13); //在begin()+2位置插入 13
cout << "3) "; PrintVector(v.begin(),v.end());
//3) 1 2 13 3 4 5
v.erase(v.begin() + 2); //删除位于 begin() + 2的元素
cout << "4) "; PrintVector(v.begin(),v.end());
//4) 1 2 3 4 5
vector<int> v2(4,100); //v2 有4个元素,都是100
v2.insert(v2.begin(),v.begin()+ 1,v.begin()+3);
//将v的一段插入v2开头
cout << "5) v2: "; PrintVector(v2.begin(),v2.end());
//5) v2: 2 3 100 100 100 100
48
v.erase(v.begin() + 1, v.begin() + 3);
//删除 v 上的一个区间,即 2,3
cout << "6) "; PrintVector(v.begin(),v.end());
//6) 1 4 5
return 0;
}
2)用vector实现二维数组
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int> > v(3);
//v 有3 个元素,每个元素都是vector<int> 容器
for(int i = 0;i < v.size(); ++i)
for(int j = 0; j < 4; ++j)
v[i].push_back(j);
for(int i = 0;i < v.size(); ++i) {
for(int j = 0; j < v[i].size(); ++j)
cout << v[i][j] << " ";
cout << endl;
}
return 0;
}
3)所有适用于 vector的操作都适用于 deque。deque还有 push_front(将元素插入到前面) 和pop_front(删除最前面的元素)操作,复杂度是O(1)
4.1.2 List双向链表
1)在任何位置插入删除都是常数时间,不支持随机存取
2)除了具有所有顺序容器都有的成员函数以外,还支持8个成员函数:
(1)push_front: 在前面插入
(2)pop_front: 删除前面的元素
(3)sort: 排序 ( list 不支持 STL 的算法 sort)
(4)remove: 删除和指定值相等的所有元素
(5)unique: 删除所有和前一个元素相同的元素(要做到元素不重复,则unique之前还需要 sort)
(6)merge: 合并两个链表,并清空被合并的那个
(7)reverse: 颠倒链表
(8)splice: 在指定位置前面插入另一链表中的一个或多个元素,并在另一链表中删除被插入的元素
3)示例程序:
#include <list>
#include <iostream>
#include <algorithm>
using namespace std;
class A {
private:
int n;
public:
A( int n_ ) { n = n_; }
friend bool operator<( const A & a1, const A & a2);
friend bool operator==( const A & a1, const A & a2);
friend ostream & operator <<( ostream & o, const A & a);
};
bool operator<( const A & a1, const A & a2) {
return a1.n < a2.n;
}
bool operator==( const A & a1, const A & a2) {
return a1.n == a2.n;
}
ostream & operator <<( ostream & o, const A & a) {
o << a.n;
return o;
}
template <class T>
void PrintList(const list<T> & lst) {
//不推荐的写法,还是用两个迭代器作为参数更好
int tmp = lst.size();
if( tmp > 0 ) {
typename list<T>::const_iterator i;
i = lst.begin();
for( i = lst.begin();i != lst.end(); i ++)
cout << * i << ",";
}
}
// typename用来说明 list<T>::const_iterator是个类型
//在vs中不写也可以
int main() {
list<A> lst1,lst2;
lst1.push_back(1);lst1.push_back(3);
lst1.push_back(2);lst1.push_back(4);
lst1.push_back(2);
lst2.push_back(10);lst2.push_front(20);
lst2.push_back(30);lst2.push_back(30);
lst2.push_back(30);lst2.push_front(40);
lst2.push_back(40);
cout << "1) "; PrintList( lst1); cout << endl;
// 1) 1,3,2,4,2,
cout << "2) "; PrintList( lst2); cout << endl;
// 2) 40,20,10,30,30,30,40,
lst2.sort();
cout << "3) "; PrintList( lst2); cout << endl;
//3) 10,20,30,30,30,40,40,
lst2.pop_front();
cout << "4) "; PrintList( lst2); cout << endl;
//4) 20,30,30,30,40,40,
lst1.remove(2); //删除所有和A(2)相等的元素
cout << "5) "; PrintList( lst1); cout << endl;
//5) 1,3,4,
lst2.unique(); //删除所有和前一个元素相等的元素
cout << "6) "; PrintList( lst2); cout << endl;
//6) 20,30,40,
lst1.merge (lst2); //合并 lst2到lst1并清空lst2
cout << "7) "; PrintList( lst1); cout << endl;
//7) 1,3,4,20,30,40,
cout << "8) "; PrintList( lst2); cout << endl;
//8)
lst1.reverse();
cout << "9) "; PrintList( lst1); cout << endl;
//9) 40,30,20,4,3,1,
lst2.push_back (100);lst2.push_back (200);
lst2.push_back (300);lst2.push_back (400);
list<A>::iterator p1,p2,p3;
p1 = find(lst1.begin(),lst1.end(),3);
p2 = find(lst2.begin(),lst2.end(),200);
p3 = find(lst2.begin(),lst2.end(),400);
lst1.splice(p1,lst2,p2, p3);
//将[p2,p3)插入p1之前,并从lst2中删除[p2,p3)
cout << "10) "; PrintList( lst1); cout << endl;
//10) 40,30,20,4,200,300,3,1,
cout << "11) "; PrintList( lst2); cout << endl;
//11) 100,400,
return 0;
}
4.2 函数对象
1)是个对象,但是用起来看上去象函数调用,实际上也执行了函数调用
class CMyAverage {
public:
double operator()( int a1, int a2, int a3 ) {
//重载 () 运算符
return (double)(a1 + a2+a3) / 3;
}
};
CMyAverage average; //函数对象
cout << average(3,2,3); //average.operator()(3,2,3) 用起来看上去象函数调用 输出 2.66667
2)函数对象的应用1:
(1)Dev C++ 中的 Accumulate 源代码1:
template<typename _InputIterator, typename _Tp>
_Tp accumulate(_InputIterator __first, _InputIterator __last, _Tp __init){
for ( ; __first != __last; ++__first)
__init = __init + *__first;
return __init;
}
(2)Dev C++ 中的 Accumulate 源代码2:
template<typename _InputIterator, typename _Tp,typename _BinaryOperation>
_Tp accumulate(_InputIterator __first, _InputIterator __last,_Tp __init,_BinaryOperation __binary_op)
{
for ( ; __first != __last; ++__first)
__init = __binary_op(__init, *__first);
return __init;
}
(3)示例程序:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
using namespace std;
int sumSquares( int total, int value)
{ return total + value * value; }
template <class T>
void PrintInterval(T first, T last){ //输出区间[first,last)中的元素
for( ; first != last; ++ first)
cout << * first << " ";
cout << endl;
}
template<class T>
class SumPowers{
private:
int power;
public:
SumPowers(int p):power(p) { }
const T operator() ( const T & total,const T & value){ //计算 value的power次方,加到total上
T v = value;
for( int i = 0;i < power - 1; ++ i)
v = v * value;
return total + v;
}
};
int main()
{
const int SIZE = 10;
int a1[] = { 1,2,3,4,5,6,7,8,9,10 };
vector<int> v(a1,a1+SIZE);
cout << "1) "; PrintInterval(v.begin(),v.end());
int result = accumulate(v.begin(),v.end(),0,SumSquares);
cout << "2) 平方和:" << result << endl;
result = accumulate(v.begin(),v.end(),0,SumPowers<int>(3));
cout << "3) 立方和:" << result << endl;
result = accumulate(v.begin(),v.end(),0,SumPowers<int>(4));
cout << "4) 4次方和:" << result;
return 0;
}
(4)实例化出:
int result = accumulate(v.begin(),v.end(),0,SumSquares);
int accumulate(vector<int>::iterator
first,vector<int>::iterator last,
int init,int ( * op)( int,int)){
for ( ; first != last; ++first)
init = op(init, *first);
return init;
}
(5)实例化出:
int result = accumulate(v.begin(),v.end(),0,SumPowers<int>(3));
int accumulate(vector<int>::iterator first,
vector<int>::iterator last,
int init, SumPowers<int> op){
for ( ; first != last; ++first)
init = op(init, *first);
return init;
}
输出:
1) 1 2 3 4 5 6 7 8
9 10
2) 平方和: 385
3) 立方和: 3025
4) 4 次方和: 25333
3)STL中函数对象应用2:
(1)STL 的 里还有以下函数对象类模板:
a)equal_to
b)greater
c)less …….这些模板可以用来生成函数对象。
(2)greater 函数对象类模板
template<class T>
struct greater : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const {
return x > y;
}
};
(3)greater 的应用
(1)list 有两个sort函数,前面例子中看到的是不带参数的sort函数,它将list中的元素按 < 规定的比较方法 升序排列。
(2)list还有另一个sort函数:可以用 op来比较大小,即 op(x,y) 为true则认为x应该排在前面。
template <class T2>
void sort(T2 op);
(3)示例1:
#include <list>
#include <iostream>
#include <iterator>
using namespace std;
class MyLess {
public:
bool operator()( const int & c1, const int & c2 ){
return (c1 % 10) < (c2 % 10);
}
};
int main(){
const int SIZE = 5;
int a[SIZE] = {5,21,14,2,3};
list<int> lst(a,a+SIZE);
lst.sort(MyLess());
ostream_iterator<int> output(cout,",");
copy( lst.begin(),lst.end(),output); cout << endl;
lst.sort(greater<int>()); //greater<int>()是个对象
//本句进行降序排序
copy( lst.begin(),lst.end(),output); cout << endl;
return 0;
}
输出:
21,2,3,14,5,
21,14,5,3,2,
(4)示例2:
#include <iostream>
#include <iterator>
using namespace std;
class MyLess{
public:
bool operator() (int a1,int a2)
{
if( ( a1 % 10 ) < (a2%10) )
return true;
else
return false;
}
};
bool MyCompare(int a1,int a2){
if( ( a1 % 10 ) < (a2%10) )
return false;
else
return true;
}
int main(){
int a[] = {35,7,13,19,12};
cout << MyMax(a,5,MyLess()) << endl;
cout << MyMax(a,5,MyCompare) << endl;
return 0;
}
输出:
19
12
template <class T, class Pred>
T MyMax( T * p, int n, Pred myless){
T tmpmax = p[0];
for( int i = 1;i < n;i ++ )
if( myless(tmpmax,p[i]))
tmpmax = p[i];
return tmpmax;
};
4)比较规则的注意事项
struct 结构名{
bool operator()( const T & a1,const T & a2) {
//若a1应该在a2前面,则返回true。
//否则返回false。
}
};
(1)排序规则返回 true,意味着 a1 必须在 a2 前面,返回 false,意味着 a1 并非必须在 a2 前面
(2)排序规则的写法,不能造成比较 a1,a2 返回 true 比较 a2,a1 也返回 true否则sort会 runtime error
(3)比较 a1,a2 返回 false 比较 a2,a1 也返回 false,则没有问题
名字(参数):像这种方式调用有三种:
1)函数名(参数)
2)函数指针(参数)
3)函数对象(参数)
4.3 关联容器
1)关联容器有set, multiset, map, multimap
(1)内部元素有序排列,新元素插入的位置取决于它的值,查找速度快。
(2)除了各容器都有的函数外,还支持以下成员函数:
a)find: 查找等于某个值 的元素(x小于y和y小于x同时不成立即为相等)
b)lower_bound : 查找某个下界
c)upper_bound : 查找某个上界
d)equal_range : 同时查找上界和下界
e)count :计算等于某个值的元素个数(x小于y和y小于x同时不成立即为相等)
f)insert: 用以插入一个元素或一个区间
2)预备知识: pair 模板
template<class _T1, class _T2>
struct pair{
typedef _T1 first_type;
typedef _T2 second_type;
_T1 first;
_T2 second;
pair(): first(), second() { }
pair(const _T1& __a, const _T2& __b): first(__a), second(__b) { }
template<class _U1, class _U2>
pair(const pair<_U1, _U2>& __p): first(__p.first), second(__p.second) { }
};
(1)map/multimap容器里放着的都是pair模版类的对象,且按first从小到大排序
(2)第三个构造函数用法示例:
pair<int,int>
p(pair<double,double>(5.5,4.6));
// p.first = 5, p.second = 4
4.3.1 multiset和set
1)multiset的定义:
template<class Key, class Pred = less<Key>,
class A = allocator<Key> >
class multiset { …… };
(1)Pred类型的变量决定了multiset 中的元素,“一个比另一个小”是怎么定义的。multiset运行过程中,比较两个元素x,y的大小的做法,就是生成一个 Pred类型的变量,假定为 op,若表达式op(x,y) 返回值为true,则 x比y小。
(2)Pred的缺省类型是 less<Key>
(3)less 模板的定义:
template<class T>
struct less : public binary_function<T, T, bool>
{ bool operator()(const T& x, const T& y) { return x < y ; } const; };
//less模板是靠 < 来比较大小的
2)multiset 的成员函数
(1)iterator find(const T & val);在容器中查找值为val的元素,返回其迭代器。如果找不到,返回end()。
(2)iterator insert(const T & val); 将val插入到容器中并返回其迭代器。
(3)void insert( iterator first,iterator last); 将区间[first,last)插入容器。
(4)int count(const T & val); 统计有多少个元素的值和val相等。
(5)iterator lower_bound(const T & val);查找一个最大的位置 it,使得[begin(),it) 中所有的元素都比 val 小。
(6)iterator upper_bound(const T & val);查找一个最小的位置 it,使得[it,end()) 中所有的元素都比 val 大。
(7)pair<iterator,iterator> equal_range(const T & val);同时求得lower_bound和upper_bound。
(8)iterator erase(iterator it);删除it指向的元素,返回其后面的元素的迭代器(Visual studio 2010上如此,但是在C++标准和Dev C++中,返回值不是这样)。
3)multiset 的用法
(1)错误示例:
#include <set>
using namespace std;
class A { };
int main() {
multiset<A> a;
a.insert( A()); //error
}
(2)multiset <A> a;就等价于multiset<A, less<A>> a;插入元素时,multiset会将被插入元素和已有元素进行比较。由于less模板是用 < 进行比较的,所以,这都要求 A 的对象能用 < 比较,即适当重载了 <
(3)正确示例:
set排序方式有两种:一个是使用重载的小于号,一个是使用函数对象
#include <iostream>
#include <set> //使用multiset须包含此文件
using namespace std;
//定义输出模板
template <class T>
void Print(T first, T last){
for(;first != last ; ++first) cout << * first << " ";
cout << endl;
}
class A {
private:
int n;
public:
A(int n_ ) { n = n_; }
friend bool operator< ( const A & a1, const A & a2 ) { return a1.n < a2.n; }
friend ostream & operator<< ( ostream & o, const A & a2 ) { o << a2.n; return o; }
friend class MyLess;
};
//定义一个比较函数对象:按照个位数比较大小
struct MyLess {
bool operator()( const A & a1, const A & a2)
//按个位数比大小
{ return ( a1.n % 10 ) < (a2.n % 10); }
};
typedef multiset<A> MSET1; //MSET1用 "<"比较大小
typedef multiset<A,MyLess> MSET2; //MSET2用 MyLess::operator()比较大小
int main(){
const int SIZE = 6;
A a[SIZE] = { 4,22,19,8,33,40 };
MSET1 m1;
m1.insert(a,a+SIZE);
m1.insert(22);
cout << "1) " << m1.count(22) << endl; //输出 1) 2
cout << "2) "; Print(m1.begin(),m1.end()); //输出 2) 4 8 19 22 22 33 40
//m1元素:4 8 19 22 22 33 40
MSET1::iterator pp = m1.find(19);
if( pp != m1.end() ) //条件为真说明找到
cout << "found" << endl;
//本行会被执行,输出 found
cout << "3) "; cout << * m1.lower_bound(22) << ","<<* m1.upper_bound(22)<< endl;
//输出 3) 22,33
//lower_bound找一个最低位他左边的都小于他
//upper_bound找一个最低的,自身和右边的都大于它
pp = m1.erase(m1.lower_bound(22),m1.upper_bound(22));
//pp指向被删元素的下一个元素
cout << "4) "; Print(m1.begin(),m1.end()); //输出 4) 4 8 19 33 40
cout << "5) "; cout << * pp << endl; //输出 5) 33
MSET2 m2; // m2里的元素按n的个位数从小到大排
m2.insert(a,a+SIZE);
cout << "6) "; Print(m2.begin(),m2.end()); //输出 6) 40 22 33 4 8 19
return 0;
}
输出:
1) 2
2) 4 8 19 22 22 33 40
3) 22,33
4) 4 8 19 33 40
5) 33
6) 40 22 33 4 8 19
4)set的用法:
(1)set的定义:
template<class Key, class Pred = less<Key>,
class A = allocator<Key> >
class set { … }
(2)插入set中已有的元素时,忽略插入
(3)示例:
#include <iostream>
#include <set>
using namespace std;
int main() {
typedef set<int>::iterator IT;
int a[5] = { 3,4,6,1,2 };
set<int> st(a,a+5); // st里是 1 2 3 4 6
pair< IT,bool> result;
result = st.insert(5); // st变成 1 2 3 4 5 6
if( result.second ) //插入成功则输出被插入元素
cout << * result.first << " inserted" << endl; //输出: 5 inserted
if( st.insert(5).second )
cout << * result.first << endl;
else
cout << * result.first << " already exists" << endl; //输出 5 already exists
pair<IT,IT> bounds = st.equal_range(4);
cout << * bounds.first << "," << * bounds.second ; //输出:4,5
return 0;
}
输出结果:
5 inserted
5 already exists
4,5
4.3.2 multimap和map
1)multimap的声明:
template<class Key, class T, class Pred = less<Key>,class A = allocator<T> >
class multimap {
….
typedef pair<const Key, T> value_type;
…….
}; //Key 代表关键字的类型
(1)multimap中的元素由 <关键字,值>组成,每个元素是一个pair对象,关键字就是first成员变量,其类型是Key
(2)multimap 中允许多个元素的关键字相同。元素按照first成员变量从小到大
排列,缺省情况下用 less<Key> 定义关键字的“小于”关系。
(3)less 模板的定义:
template<class T>
struct less : public binary_function<T, T, bool>
{ bool operator()(const T& x, const T& y) { return x < y ; } const; };
//less模板是靠 < 来比较大小的
2)multimap示例:
#include <iostream>
#include <map>
using namespace std;
int main() {
typedef multimap<int,double,less<int> > mmid;
mmid pairs;
cout << "1) " << pairs.count(15) << endl;
pairs.insert(mmid::value_type(15,2.7));//typedef pair<const Key, T> value_type;
pairs.insert(mmid::value_type(15,99.3));
cout << “2) ” << pairs.count(15) << endl; //求关键字等于某值的元素个数
pairs.insert(mmid::value_type(30,111.11));
pairs.insert(mmid::value_type(10,22.22));
pairs.insert(mmid::value_type(25,33.333));
pairs.insert(mmid::value_type(20,9.3));
for( mmid::const_iterator i = pairs.begin();
i != pairs.end() ;i ++ )
cout << "(" << i->first << "," << i->second << ")" << ",";
}
输出:
1) 0
2) 2
(10,22.22),(15,2.7),(15,99.3),(20,9.3),(25,33.333),(30,111.11)
3)multimap例题:
一个学生成绩录入和查询系统,
接受以下两种输入:
Add name id score
Query score
name是个字符串,中间没有空格,代表学生姓名。id是个整数,代表学号。score是个整数,表示分数。学号不会重复,分数和姓名都可能重复。两种输入交替出现。第一种输入表示要添加一个学生的信息,碰到这种输入,就记下学生的姓名、id和分数。第二种输入表示要查询,碰到这种输入,就输出已有记录中分数比score低的最高分获得者的姓名、学号和分数。如果有多个学生都满足条件,就输出学号最大的那个学生的信息。如果找不到满足条件的学生,则输出“Nobody”
输入样例:
Add Jack 12 78
Query 78
Query 81
Add Percy 9 81
Add Marry 8 81
Query 82
Add Tom 11 79
Query 80
Query 81
输出果样例:
Nobody
Jack 12 78
Percy 9 81
Tom 11 79
Tom 11 79
#include <iostream>
#include <map> //使用multimap需要包含此头文件
#include <string>
using namespace std;
class CStudent{
public:
struct CInfo //类的内部还可以定义类
{
int id;
string name;
};
int score;
CInfo info; //学生的其他信息
};
typedef multimap<int, CStudent::CInfo> MAP_STD;
int main() {
MAP_STD mp;
CStudent st;
string cmd;
while( cin >> cmd ) {
if( cmd == "Add") {
cin >> st.info.name >> st.info.id >> st.score ;
mp.insert(MAP_STD::value_type(st.score,st.info ));
}
else if( cmd == "Query" ){
int score;
cin >> score;
MAP_STD::iterator p = mp.lower_bound (score);
if( p!= mp.begin()) {
--p;
score = p->first; //比要查询分数低的最高分
MAP_STD::iterator maxp = p;
int maxId = p->second.id;
for( ; p != mp.begin() && p->first == score; --p) {
//遍历所有成绩和score相等的学生
if( p->second.id > maxId ) {
maxp = p;
maxId = p->second.id ;
}
}
if( p->first == score) {
//如果上面循环是因为 p == mp.begin()
// 而终止,则p指向的元素还要处理
if( p->second.id > maxId ) {
maxp = p;
maxId = p->second.id ;
}
}
cout << maxp->second.name << " " << maxp->second.id << " "
<< maxp->first << endl;
}
else
//lower_bound的结果就是 begin,说明没人分数比查询分数低
cout << "Nobody" << endl;
}
}
return 0;
}
4)map:
(1)声明:
template<class Key, class T, class Pred = less<Key>,
class A = allocator<T> >
class map {
….
typedef pair<const Key, T> value_type;
…….
};
2)map 中的元素都是pair模板类对象。关键字(first成员变量)各不相同。元素按照关键字从小到大排列,缺省情况下用 less<Key>,即“<” 定义“小于”
3)map的[ ]成员函数
(1)若pairs为map模版类的对象,pairs[key]返回对关键字等于key的元素的值(second成员变量)的引用。若没有关键字为key的元素,则会往pairs里插入一个关键字为key的元素,其值用无参构造函数初始化,并返回其值的引用.
map<int,double> pairs;
pairs[50] = 5;
//会修改pairs中关键字为50的元素,使其值变成5。
//若不存在关键字等于50的元素,则插入此元素,并使其值变为5。
4)map示例:
#include <iostream>
#include <map>
using namespace std;
template <class Key,class Value>
ostream & operator <<( ostream & o, const pair<Key,Value> & p){
o << "(" << p.first << "," << p.second << ")";
return o;
}
int main() {
typedef map<int, double,less<int> > mmid;
mmid pairs;
cout << "1) " << pairs.count(15) << endl;
pairs.insert(mmid::value_type(15,2.7));
pairs.insert(make_pair(15,99.3)); //make_pair生成一个pair对象
cout << "2) " << pairs.count(15) << endl;
pairs.insert(mmid::value_type(20,9.3));
mmid::iterator i;
cout << "3) ";
for( i = pairs.begin(); i != pairs.end();i ++ )
cout << * i << ",";
cout << endl;
cout << "4) ";
int n = pairs[40];//如果没有关键字为40的元素,则插入一个
for( i = pairs.begin(); i != pairs.end();i ++ )
cout << * i << ",";
cout << endl;
cout << "5) ";
pairs[15] = 6.28; //把关键字为15的元素值改成6.28
for( i = pairs.begin(); i != pairs.end();i ++ )
cout << * i << ",";
}
输出:
1) 0
2) 1
3) (15,2.7),(20,9.3),
4) (15,2.7),(20,9.3),(40,0),
5) (15,6.28),(20,9.3),(40,0)
4.4 容器适配器
4.4.1 stack(栈)
1)stack 是后进先出的数据结构,只能插入,删除,访问栈顶的元素。
2)可用 vector, list, deque来实现。缺省情况下,用deque实现。用 vector和deque实现,比用list实现性能好。
template<class T, class Cont = deque<T> >
class stack {
…..
};
3)stack 上可以进行以下操作:
(1)push 插入元素
(2)pop 弹出元素
(3)top 返回栈顶元素的引用
4.4.2 queue(队列)
1)和stack 基本类似,可以用 list和deque实现。缺省情况下用deque实现。
template<class T, class Cont = deque<T> >
class queue {
……
};
2)同样也有push, pop, top函数。但是push发生在队尾;pop, top发生在队头。先进先出。有 back成员函数可以返回队尾元素的引用
4.4.3 priority_queue(优先队列)
1)声明:
(1)push、pop 时间复杂度O(logn)
(2)top()时间复杂度O(1)
template <class T, class Container = vector<T>,
class Compare = less<T> >
class priority_queue;
2)和 queue类似,可以用vector和deque实现。缺省情况下用vector实现。
3)priority_queue 通常用堆排序技术实现,保证最大的元素总是在最前面。即执行pop操作时,删除的是最大的元素;执行top操作时,返回的是最大元素的常引用。默认的元素比较器是less<T>。
4)使用示例:
#include <queue>
#include <iostream>
using namespace std;
int main(){
priority_queue<double> pq1;
pq1.push(3.2); pq1.push(9.8); pq1.push(9.8); pq1.push(5.4);
while( !pq1.empty() ) {
cout << pq1.top() << " ";
pq1.pop();
} //上面输出 9.8 9.8 5.4 3.2
cout << endl;
priority_queue<double,vector<double>,greater<double> > pq2;
pq2.push(3.2); pq2.push(9.8); pq2.push(9.8); pq2.push(5.4);
while( !pq2.empty() ) {
cout << pq2.top() << " ";
pq2.pop();
}
//上面输出 3.2 5.4 9.8 9.8
return 0;
}
5)stack,queue,priority_queue 都有
(1)empty() 成员函数用于判断适配器是否为空
(2)size() 成员函数返回适配器中元素个数
6)容器适配器需要指出排序规则,默认使用less<T>,最大的在最上面