std::valarray<T>::operator[]

Retrieve single elements or portions of the array.

# Declarations

const T& operator[]( std::size_t pos ) const;
T& operator[]( std::size_t pos );
std::valarray<T> operator[]( std::slice slicearr ) const;
std::slice_array<T> operator[]( std::slice slicearr );
std::valarray<T> operator[]( const std::gslice& gslicearr ) const;
std::gslice_array<T> operator[]( const std::gslice& gslicearr );
std::valarray<T> operator[]( const std::valarray<bool>& boolarr ) const;
std::mask_array<T> operator[]( const std::valarray<bool>& boolarr );
std::valarray<T> operator[]( const std::valarray<std::size_t>& indarr ) const;
std::indirect_array<T> operator[]( const std::valarray<std::size_t>& indarr );

# Parameters

# Notes

For proper std::valarray values a, b and proper std::size_t values i, j, all of the following expressions always evaluate to true:

References become invalid on resize() or when the array is destructed.

For overloads (3,5,7,9), The function can be implemented with the return type different from std::valarray. In this case, the replacement type has the following properties:

Slice/mask/indirect index accesses do not chain: v[v == n][std::slice(0, 5, 2)] = x; is an error because std::mask_array (the type of v[v == n]) does not have operator[].

# Example

#include <cstddef>
#include <iomanip>
#include <iostream>
#include <valarray>
 
int main() 
{
    std::valarray<int> data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
 
    std::cout << "Initial valarray:   ";
    for (int n : data)
        std::cout << std::setw(3) << n;
    std::cout << '\n';
 
    data[data > 5] = -1; // valarray<bool> overload of operator[]
    // the type of data > 5 is std::valarray<bool>
    // the type of data[data > 5] is std::mask_array<int>
 
    std::cout << "After v[v > 5] = -1:";
    for (std::size_t n = 0; n < data.size(); ++n) 
        std::cout << std::setw(3) << data[n]; // regular operator[]
    std::cout << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 389C++98the return type of overload (1) was Tcorrected to const T&
LWG 430C++98the behavior was unclear for overloads(3-10) if an invalid subset is specifiedthe behavior is undefined in this case