实际上在 Vector
与 SortedVector
这两个类中,没有太多内容,主要提供了一些给外部调用的接口而已。不过也有一些需要注意的内容,比如抽象类中的纯虚函数的实现,以及自定义的比较函数等等。
相关文章
- Android Utils 之 Vector 学习笔记(一)—— VectorImpl 代码分析
- Android Utils 之 Vector 学习笔记(二)—— SortedVectorImpl 代码分析
- Android Utils 之 Vector 学习笔记(三)—— Vector 与 SortedVector 代码分析
- Android Utils 之 Vector 学习笔记(四,完结)—— KeyedVector 与 DefaultKeyedVector 代码分析
Vector
Vectoc
类继承自 VectorImpl
,它的大部分功能都是通过直接内部调用父类的函数来实现的。因此这个类的结构与实现都非常简单,以至于只需要一个头文件就能全部包含。
根据代码中的注释可以知道,这一主模板 Vector
类在使用 VectorImpl
时确保了类型安全性。这个类是开放给用户使用的。这个 Vector 和标准模板库中的那个用途应该是一样的,不过在实现上应该有所不同,具体差异其实不必深究,能用就行……
类定义
文件路径:system\core\libutils\include\utils\Vector.h
代码解释:
- 第 2 行:声明了
SortedVector
类,因为此处没有引用相应的头文件,但后面在构造函数中会用到它。 - 第 11 行:注意此处用的是私有继承。
- 第 36~133 行:这里全是关于增、删、查找这类的基本操作的调用接口,通过函数名就可以很好地知道它的功能,如果有不清楚的地方,可以看相应函数的注释,都解释得很清楚了。
- 第 139~143 行:声明了两个函数指针,用于指向自定义的比较函数。排序函数则负责基于比较函数对 Vector 进行排序(排序具体实现在父类中,根据前两章的分析可以知道,用的是插入排序算法)。
- 第 153~167 行:这里声明的函数以及迭代器
iterator
是为了在一定程度上兼容 STL 中的Vector
类。用过 STL 中的Vector
的人应该比较熟悉这些操作了,主要就是基于iterator
来对 Vector 中元素进行访问、控制、遍历等(注意使用const_iterator
时不能对元素内容进行操作)。 - 第 170~176 行:这些是父类中的纯虚函数,此处必须给出相应的具体实现。
template <typename TYPE>
class SortedVector;
/*!
* The main templated vector class ensuring type safety
* while making use of VectorImpl.
* This is the class users want to use.
*/
template <class TYPE>
class Vector : private VectorImpl
{
public:
typedef TYPE value_type;
/*!
* Constructors and destructors
*/
Vector();
Vector(const Vector<TYPE>& rhs);
explicit Vector(const SortedVector<TYPE>& rhs);
virtual ~Vector();
/*! copy operator */
const Vector<TYPE>& operator = (const Vector<TYPE>& rhs) const;
Vector<TYPE>& operator = (const Vector<TYPE>& rhs);
const Vector<TYPE>& operator = (const SortedVector<TYPE>& rhs) const;
Vector<TYPE>& operator = (const SortedVector<TYPE>& rhs);
/*
* empty the vector
*/
inline void clear() { VectorImpl::clear(); }
/*!
* vector stats
*/
//! returns number of items in the vector
inline size_t size() const { return VectorImpl::size(); }
//! returns whether or not the vector is empty
inline bool isEmpty() const { return VectorImpl::isEmpty(); }
//! returns how many items can be stored without reallocating the backing store
inline size_t capacity() const { return VectorImpl::capacity(); }
//! sets the capacity. capacity can never be reduced less than size()
inline ssize_t setCapacity(size_t size) { return VectorImpl::setCapacity(size); }
/*!
* set the size of the vector. items are appended with the default
* constructor, or removed from the end as needed.
*/
inline ssize_t resize(size_t size) { return VectorImpl::resize(size); }
/*!
* C-style array access
*/
//! read-only C-style access
inline const TYPE* array() const;
//! read-write C-style access
TYPE* editArray();
/*!
* accessors
*/
//! read-only access to an item at a given index
inline const TYPE& operator [] (size_t index) const;
//! alt