关于size_t, ptrdiff_t, size_type, difference_type

本文介绍了size_t和ptrdiff_t两种类型的区别与应用场景。size_t为无符号类型,用于表示数组长度或下标;ptrdiff_t为带符号类型,用于表示同一数组中两个指针间的差距。这两种类型分别对应于STL容器中的size_type和difference_type。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自http://www.cnblogs.com/liulipeng/archive/2012/10/08/2715246.html

size_t是unsigned类型,用于指明数组长度或下标,它必须是一个正数,std::size_t.设计size_t就是为了适应多个平台,其引入增强了程序在不同平台上的可移植性。

ptrdiff_t是signed类型,用于存放同一数组中两个指针之间的差距,它可以使负数,std::ptrdiff_t.同上,使用ptrdiff_t来得到独立于平台的地址差值.

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

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

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

#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、付费专栏及课程。

余额充值