关于size_t, ptrdiff_t, size_type, difference_type

本文详细介绍了 C++ 中 std::size_t 和 std::ptrdiff_t 的用法,前者用于表示数组长度及容器元素数量,必须为非负数;后者则用于表示同一数组中两个指针间的差距,可以是负数。此外,还讲解了容器特有的 size_type 和 difference_type 的定义及使用场景。

size_t unsigned 类型,用于指明数组长度或下标,它必须是一个正数, std::size_t

ptrdiff_t signed 类型,用于存放同一数组中两个指针之间的差距,它可以使负数, std::ptrdiff_t.

size_type unsigned 类型 , 表示容器中元素长度或者下标, vector<int>::size_type i = 0;

difference_type signed 类型 , 表示迭代器差距, vector<int>:: difference_type = iter1-iter2.

前二者位于标准类库 std 内,后二者专为 STL 对象所拥有。

 

http://blog.youkuaiyun.com/zhaowei123191/archive/2010/05/23/5617559.aspx

#ifndef ALLOCATOR_HPP #define ALLOCATOR_HPP #include <stddef.h> #include <limits> template <typename T> class Allocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; //Allocator::rebind<T2>::other template <typename V> struct rebind { typedef Allocator<V> other; }; pointer address(reference value) const { return &value; } const_pointer address(const_reference value) const { return &value; } Allocator() throw() { } Allocator(const Allocator &) throw() { } //不同类型的allcator可以相互复制 template <typename V> Allocator(const Allocator<V> &other) { } ~Allocator() throw() { } //最多可以分配的数目 size_type max_size() const throw() { return std::numeric_limits<size_type>::max() / sizeof(T); } //分配内存,返回该类型的指针 pointer allocate(size_type num) { return (pointer)(::operator new(num * sizeof(T))); } //执行构造函数,构建一个对象 void construct(pointer p, const T &value) { new ((void*)p) T(value); } //销毁对象 void destroy(pointer p) { p->~T(); } //释放内存 void deallocate(pointer p, size_type num) { ::operator delete((void *)p); } }; template <typename T, typename V> bool operator==(const Allocator<T> &, const Allocator<V> &) throw() { return true; } template <typename T, typename V> bool operator!=(const Allocator<T> &, const Allocator<V> &) throw() { return false; } #endif讲解这段代码
最新发布
03-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值