我了解了cppreference中的std::vector
数据类型。目前在成员类型中,我看到了iterator
data_type。
我确实知道iterator
要求LegacyRandomAccessIterator
。但是如何使用自己的模板类定义LegacyRandomAccessIterator iterator
data_type?
template <typename T>
class vec {
typedef T value_type;//correct
typedef LegacyRandomAccessIterator iterator;//error
};
我尝试使用
typedef LegacyRandomAccessIterator iterator
,但失败了。如何在自定义类中定义iterator
代表LegacyRandomAccessIterator
? 最佳答案
您需要一个具有以下运算符的类型,其含义与使用指针的含义相同。
template <typename T>
class vec_iterator
{
typedef std::ptrdiff_t difference_type;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef std::random_access_iterator_tag iterator_category;
vec_iterator();
reference operator*();
pointer operator->();
vec_iterator& operator++();
vec_iterator operator++(int);
vec_iterator& operator--();
vec_iterator operator--(int);
vec_iterator& operator+=(difference_type);
vec_iterator& operator-=(difference_type);
reference operator[](difference_type);
};
template <typename T>
bool operator ==(vec_iterator<T>, vec_iterator<T>);
template <typename T>
bool operator !=(vec_iterator<T>, vec_iterator<T>);
template <typename T>
bool operator <(vec_iterator<T>, vec_iterator<T>);
template <typename T>
bool operator <=(vec_iterator<T>, vec_iterator<T>);
template <typename T>
bool operator >(vec_iterator<T>, vec_iterator<T>);
template <typename T>
bool operator >=(vec_iterator<T>, vec_iterator<T>);
template <typename T>
vec_iterator<T> operator +(vec_iterator<T>, typename vec_iterator<T>::difference_type);
template <typename T>
vec_iterator<T> operator +(typename vec_iterator<T>::difference_type, vec_iterator<T>);
template <typename T>
vec_iterator<T> operator -(vec_iterator<T>, typename vec_iterator<T>::difference_type);
template <typename T>
vec_iterator<T> operator -(typename vec_iterator<T>::difference_type, vec_iterator<T>);
请注意,
T*
是满足RandomAccessIterator的类型。以
vec_iterator
作为最左侧参数的非成员可以改为成员。除了提供difference_type
,value_type
,pointer
,reference
和iterator_category
外,您还可以使用这些typedef提供(部分)专业化std::iterator_traits<vec_iterator<T>>
。关于c++ - C++将Typedef与LegacyRandomAccessIterator一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57456285/