Spec-Zone.ru › C++

std::counted_iterator<I>::operator[]

constexpr decltype(auto) operator[]( std::iter_difference_t<I> n ) const
    requires std::random_access_iterator<I>;
(since C++20)

Accesses the element at specified relative location.

If count() > n is false, the behavior is undefined.

(until C++26)

If count() > n is false:

  • If the implementation is hardened, a contract violation occurs.
  • If the implementation is not hardened, the behavior is undefined.
(since C++26)

Parameters

n - position relative to current location

Return value

base()[n]

Example

#include <array>
#include <iostream>
#include <iterator>
#include <list>

int main()
{
    std::array array{'A', 'B', 'C', 'D', 'E'};
    
    std::counted_iterator it{array.begin() + 1, /*count:*/ 3};
    
    for (int i{}; i != it.count(); ++i)
        std::cout << it[i] << ' ';
    std::cout << '\n';
    
    for (int i{}; i != it.count(); ++i)
        it[i] += ('E' - 'A');
    
    for (int i{}; i != it.count(); ++i)
        std::cout << it[i] << ' ';
    std::cout << '\n';
    
    std::list list{'X', 'Y', 'Z', 'W'};
    std::counted_iterator it2{list.begin(), 3};
//  char x = it2[0]; // Error: requirement `random_access_iterator` was not satisfied.
    std::cout << *it2 << '\n'; // OK
}

Output:

B C D
F G H
X

See also

operator*operator->
accesses the pointed-to element
(public member function)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/iterator/counted_iterator/operator_at

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API