C++标准模板(STL)- 迭代器库 - 迭代器操作 - 返回指向容器或数组结尾的迭代器

迭代器库-迭代器操作

 
迭代器库提供了五种迭代器的定义,同时还提供了迭代器特征、适配器及相关的工具函数。

迭代器分类


迭代器共有五 (C++17 前)六 (C++17 起)种:遗留输入迭代器 (LegacyInputIterator) 、遗留输出迭代器 (LegacyOutputIterator) 、遗留向前迭代器 (LegacyForwardIterator) 、遗留双向迭代器 (LegacyBidirectionalIterator) 、遗留随机访问迭代器 (LegacyRandomAccessIterator) ,及 遗留连续迭代器 (LegacyContiguousIterator) (C++17 起)。

迭代器的分类的依据并不是迭代器的类型,而是迭代器所支持的操作。换句话说,某个类型只要支持相应的操作,就可以作为迭代器使用。例如,完整对象类型指针支持所有遗留随机访问迭代器 (LegacyRandomAccessIterator) 要求的操作,于是任何需要遗留随机访问迭代器 (LegacyRandomAccessIterator) 的地方都可以使用指针。

迭代器的所有类别(除了遗留输出迭代器 (LegacyOutputIterator) 和遗留连续迭代器 (LegacyContiguousIterator) )能组织到层级中,其中更强力的迭代器类别(如遗留随机访问迭代器 (LegacyRandomAccessIterator) )支持较不强力的类别(例如遗留输入迭代器 (LegacyInputIterator) )的所有操作。若迭代器落入这些类别之一且亦满足遗留输出迭代器 (LegacyOutputIterator) 的要求,则称之为可变 迭代器并且支持输入还有输出。称非可变迭代器为常迭代器。

返回指向容器或数组结尾的迭代器

std::end, 
std::cend

template< class C >
auto end( C& c ) -> decltype(c.end());

(1)(C++11 起)
(C++17 前)

template< class C >
constexpr auto end( C& c ) -> decltype(c.end());

(C++17 起)

template< class C >
auto end( const C& c ) -> decltype(c.end());

(1)(C++11 起)
(C++17 前)

template< class C >
constexpr auto end( const C& c ) -> decltype(c.end());

(C++17 起)

template< class T, std::size_t N >
T* end( T (&array)[N] );

(2)(C++11 起)
(C++14 前)

template< class T, std::size_t N >
constexpr T* end( T (&array)[N] ) noexcept;

(C++14 起)
template< class C >

constexpr auto cend( const C& c ) noexcept(/* see below */)

    -> decltype(std::end(c));
(3)(C++14 起)

返回指向给定容器 c 或数组 array 结尾(即最末元素的后一元素)的迭代器。这些模板依赖于拥有合理实现的 C::end() 。

1) 准确返回 c.end() ,典型地是指向 c 所代表的序列末尾后一位置的迭代器。若 C 是标准容器 (Container) ,则在 c 非 const 限定时返回 C::iterator ,否则返回 C::const_iterator 。

2) 返回指向数组 array 末尾的指针。

3) 准确返回 std::end(c) ,这里 c 始终当做 const 限定。若 C 是标准容器 (Container) ,则始终返回 C::const_iterator 。

参数

c-拥有 end 方法的容器
array-任意类型的数组

返回值

指向 carray 结尾的迭代器。注意容器或数组的结尾定义为最后一个合法元素的下一个元素。

异常

3)noexcept 规定:  

noexcept(noexcept(std::end(c)))

注意

除了包含于 <iterator> ,若包含下列任一头文件,则保证 std::endstd::cend 可用: <array><deque><forward_list><list><map><regex><set><span> (C++20 起) 、 <string><string_view> (C++17 起) 、 <unordered_map><unordered_set><vector>

用户定义重载

可为不暴露适合的 end() 成员函数的类提供 end 的自定义重载。标准库已提供下列重载:

std::end(std::initializer_list)

(C++11)

特化 std::end
(函数模板)

std::end(std::valarray)

(C++11)

特化的 std::end
(函数模板)

begin(std::filesystem::directory_iterator)end(std::filesystem::directory_iterator)

基于范围的 for 循环支持
(函数)

begin(std::filesystem::recursive_directory_iterator)end(std::filesystem::recursive_directory_iterator)

基于范围的 for 循环支持
(函数)

可能实现

namespace std
{
/// initializer_list
template<class _E>
class initializer_list
{
public:
    typedef _E 		value_type;
    typedef const _E& 	reference;
    typedef const _E& 	const_reference;
    typedef size_t 		size_type;
    typedef const _E* 	iterator;
    typedef const _E* 	const_iterator;
 
private:
    iterator			_M_array;
    size_type			_M_len;
 
    // The compiler can call a private constructor.
    constexpr initializer_list(const_iterator __a, size_type __l)
        : _M_array(__a), _M_len(__l) { }
 
public:
    constexpr initializer_list() noexcept
        : _M_array(0), _M_len(0) { }
 
    // Number of elements.
    constexpr size_type
    size() const noexcept
    {
        return _M_len;
    }
 
    // First element.
    constexpr const_iterator
    begin() const noexcept
    {
        return _M_array;
    }
 
    // One past the last element.
    constexpr const_iterator
    end() const noexcept
    {
        return begin() + size();
    }
};
 
/**
 *  @brief  Return an iterator pointing to the first element of
 *          the initializer_list.
 *  @param  __ils  Initializer list.
 */
template<class _Tp>
constexpr const _Tp*
begin(initializer_list<_Tp> __ils) noexcept
{
    return __ils.begin();
}
 
/**
 *  @brief  Return an iterator pointing to one past the last element
 *          of the initializer_list.
 *  @param  __ils  Initializer list.
 */
template<class _Tp>
constexpr const _Tp*
end(initializer_list<_Tp> __ils) noexcept
{
    return __ils.end();
}
}

调用示例

#include <iostream>
#include <sstream>
#include <iterator>
#include <fstream>
#include <numeric>
#include <algorithm>
#include <vector>
#include <typeinfo>
#include <time.h>

struct Cell
{
    int x;
    int y;

    Cell() = default;
    Cell(int a, int b): x(a), y(b) {}

    Cell(const Cell &cell)
    {
        x = cell.x;
        y = cell.y;
    }

    Cell(Cell &cell)
    {
        x = cell.x;
        y = cell.y;
        cell.x = 0;
        cell.y = 0;
    }

    Cell &operator +=(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator +(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator *(const Cell &cell)
    {
        x *= cell.x;
        y *= cell.y;
        return *this;
    }

    Cell &operator ++()
    {
        x += 1;
        y += 1;
        return *this;
    }

    bool operator <(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y < cell.y;
        }
        else
        {
            return x < cell.x;
        }
    }

    bool operator ==(const Cell &cell) const
    {
        return x == cell.x && y == cell.y;
    }
};

std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
    os << "{" << cell.x << "," << cell.y << "}";
    return os;
}

std::istream &operator>>(std::istream &is, Cell &cell)
{
    is >> cell.x;
    is >> cell.y;
    return is;
}

// 定义一个简单的迭代器适配器
template<typename _Iterator>
class move_iterator : public std::move_iterator<_Iterator>
{
public:
    // 使用基类的构造函数
    using std::move_iterator<_Iterator>::move_iterator;

    // 可以在此添加其他成员函数,如有需要
};

template< class BDIter >
void alg(BDIter, BDIter, std::input_iterator_tag)
{
    //遗留输入迭代器
    std::cout << "alg() called for input iterator" << std::endl;
}

template< class BDIter >
void alg(BDIter, BDIter, std::output_iterator_tag)
{
    //遗留输出迭代器
    std::cout << "alg() called for output iterator" << std::endl;
}

template< class BDIter >
void alg(BDIter, BDIter, std::forward_iterator_tag)
{
    //遗留向前迭代器
    std::cout << "alg() called for forward iterator" << std::endl;
}

template< class BDIter >
void alg(BDIter, BDIter, std::bidirectional_iterator_tag)
{
    //遗留双向迭代器
    std::cout << "alg() called for bidirectional iterator" << std::endl;
}

template <class RAIter>
void alg(RAIter, RAIter, std::random_access_iterator_tag)
{
    //遗留随机访问迭代器
    std::cout << "alg() called for random-access iterator" << std::endl;
}

template< class Iter >
void alg(Iter first, Iter last)
{
    alg(first, last,
        typename std::iterator_traits<Iter>::iterator_category());
}

int main()
{
    std::cout << std::boolalpha;

    std::mt19937 g{std::random_device{}()};
    srand((unsigned)time(NULL));

    auto generate = []()
    {
        int n = std::rand() % 10 + 110;
        Cell cell{n, n};
        return cell;
    };

    //3) 构造拥有 count 个有值 value 的元素的容器。
    std::vector<Cell> vector1(6, generate());
    std::generate(vector1.begin(), vector1.end(), generate);
    std::cout << "vector1:  ";
    std::copy(vector1.begin(), vector1.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;

    //1) 准确返回 c.begin() ,典型地是指向 c 所代表的序列起始的迭代器。若 C 是标准容器 (Container) ,
    //则在 c 不是 const 限定时返回 C::iterator ,否则返回 C::const_iterator 。
    std::cout << "vector1:  ";
    std::copy(std::begin(vector1), std::end(vector1), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << "typeid(std::begin(vector1)).name():   "
              << typeid(std::begin(vector1)).name() << std::endl;
    std::cout << "typeid(std::end(vector1)).name():   "
              << typeid(std::end(vector1)).name() << std::endl;

    //2) 返回指向 array 起始的指针。
    char pArray[] = "I am a handsome programmer.";
    std::cout << "pArray:  ";
    std::copy(std::begin(pArray), std::end(pArray), std::ostream_iterator<char>(std::cout, " "));
    std::cout << std::endl;
    std::cout << "typeid(std::begin(pArray)).name():   "
              << typeid(std::begin(pArray)).name() << std::endl;
    std::cout << "typeid(std::end(pArray)).name():   "
              << typeid(std::end(pArray)).name() << std::endl;
    return 0;
}

输出

vector1:  {115,115} {115,115} {115,115} {110,110} {117,117} {112,112}
vector1:  {115,115} {115,115} {115,115} {110,110} {117,117} {112,112}
typeid(std::begin(vector1)).name():   N9__gnu_cxx17__normal_iteratorIP4CellSt6vectorIS1_SaIS1_EEEE
typeid(std::end(vector1)).name():   N9__gnu_cxx17__normal_iteratorIP4CellSt6vectorIS1_SaIS1_EEEE
pArray:  I   a m   a   h a n d s o m e   p r o g r a m m e r .
typeid(std::begin(pArray)).name():   Pc
typeid(std::end(pArray)).name():   Pc

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值