命名空间
变体
操作

std::reverse_iterator<Iter>::operator[]

来自 cppreference.cn
 
 
迭代器库
迭代器概念
迭代器原语
算法概念和工具
间接可调用概念
常用算法要求
(C++20)
(C++20)
(C++20)
工具
(C++20)
迭代器适配器
范围访问
(C++11)(C++14)
(C++14)(C++14)  
(C++11)(C++14)
(C++14)(C++14)  
(C++17)(C++20)
(C++17)
(C++17)
 
 
/* unspecified */ operator[]( difference_type n ) const;
(constexpr since C++17)

返回到指定相对位置的元素的引用。

目录

[编辑] 参数

n - 相对于当前位置的位置

[编辑] 返回值

current[-n - 1]

[编辑] 注释

返回类型被 LWG issue 386 更改为 unspecified,因为底层迭代器的 operator[] 的返回类型在当时也是 unspecified。

然而,从 N3066 开始,LegacyRandomAccessIteratoroperator[] 的返回类型必须可转换为 reference。在所有常见的实现中,返回类型都被声明为 reference。另请参阅 LWG issue 2595

[编辑] 示例

#include <array>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <list>
#include <vector>
 
int main()
{
    int a[]{0, 1, 2, 3};
    std::reverse_iterator<int*> iter1{std::rbegin(a)};
    for (std::size_t i{}; i != std::size(a); ++i)
        std::cout << iter1[i] << ' '; // decltype(iter1[i]) is int&
    std::cout << '\n';
 
    std::vector v{0, 1, 2, 3};
    std::reverse_iterator<std::vector<int>::iterator> iter2{std::rbegin(v)};
    for (std::size_t i{}; i != std::size(v); ++i)
        std::cout << iter2[i] << ' '; // decltype(iter2[i]) is int&
    std::cout << '\n';
 
    // constexpr context
    constexpr static std::array<int, 4> z{0, 1, 2, 3};
    constexpr std::reverse_iterator<decltype(z)::const_iterator> iter3{std::crbegin(z)};
    static_assert(iter3[1] == 2);
 
    std::list li{0, 1, 2, 3};
    std::reverse_iterator<std::list<int>::iterator> iter4{std::rbegin(li)};
    *iter4 = 42;   // OK
//  iter4[0] = 13; // Compilation error: the underlying iterator
                   // does not model the random access iterator
}

输出

3 2 1 0
3 2 1 0

[编辑] 缺陷报告

以下行为更改缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
LWG 386 C++98 返回类型为 reference 设为 unspecified

[编辑] 参见

访问指向的元素
(public member function) [编辑]