10 特殊容器
10.1 堆栈——<stack>
1、核心接口
push();top()(最后一个被插入的元素); pop()(移除最后一个被插入的元素,无返回值)。
10.2 队列——<queue>
1、核心接口
push();front()(返回第一个插入的元素);back()(返回最后一个元素);pop()(移除第一个插入的元素,无返回值)。
10.3 priority queue——<queue>
namespace std{
template <class T, class Container = vector<T>,
class Comare = less<typename Container::value_type>
class priority_queue;
}//内部实现使用make_heap(),less<>对应最大堆
1、核心接口
push(),top()(对于less<>,返回最大值),pop()
部分构造函数:
priority(const CompFunc& op, const Container& cont);
priotity(InputIterator beg, InputOterator end, const Comfunc& op);
10.4 bitset——<bitset>
namespace std{
template <size_t Bits>
class bitset;
}
2、class bitset详细讨论
(1)生成、拷贝和销毁
bitset()默认构造函数,所有位初始化为0
bitset(unsigned long value)
bitset(const string& str, string::size_type str_idx, string::size_type str_num) //str_idx>str.size,抛出out_of_range异常;如果有的字符不是0或1,抛出invalid_argument异常。这个构造函数时template member(参数型别必须和调用端所提供的对象的型别完全吻合),所以不支持const char*到string的隐式类型转换。
(2)非变动性操作
size()
cout() //位值是1的为个数
any() //判断是否有任何位为1
none() //判断是否都没有设为1
test(idx) //idx>size()抛出out_of_range异常
operator ==判断*this和bits的所有位是否相等
operator !=
(3)变动性算法
set() 所有位设为1 ;set(size_t idx);set (idx, int value)
reset();reset(idx)
filp();filp(idx)
operator ^= ; operator |= ; operator &=
operator <<=(size_t num) 左移num个位置; operator >>=(size_t num)
(4)使用operator[ ]存取位
bitset<bits>::reference bitset<bits>::operator[ ](zise_t idx) //使用代理模式,使得返回值成为一个可以变动的左值
bool bitset<bits>::operator[ ](zise_t idx) const
bitset<50> flags;
falgs[42] = true;
flags [13] = flags[42];
flags[42].flip();
if(flags[13]){flags[10] = ~flags[42];}
(5)产生新的bitset
bitset<bits> bitset<bits>::operator ~() const //产生一个新的bitset,以*this的位翻转作为初值
operator <<(size_t num) ; operator>>(num)
bitset<bits> operator &(const bitset<bits>& bits1,const bitset<bits>& bits2 )
operatot |;operator ^;
(6)型别转换
unsigned long bitset<bits>::to_ulong() const //如果unsigned long不足以表现这个整数,抛出overflow_error异常
string bitset<bits>::to_string() cosnt
注意:这是一个template成员函数,其返回值型别被参数化了调用方式如下
bitset<50> b; b.template to_string<char,char_traits<char>, cllocator<char> >();
(7)I/O操作
istream& operator >>(istream& strm, bitset<bits>& bits)
//读取行为一直进行下去,直到:读取结束;strm出现end-of-file符号;下一个字符不是0也不是1。
ostream& operator<< (ostream& strm,const bitset<bits>& bits)