member func: at

defination

reference at ( size_type n );
const_reference at ( size_type n ) const;

Returns a reference to the element at position n in the array.

The function automatically checks whether n is within the bounds of valid elements in the container, throwing an out_of_range exception if it is not (i.e., if n is greater than, or equal to, its size). This is in contrast with member operator[], that does not check against bounds.

Parameters

Position of an element in the array. If this is greater than, or equal to, the array size, an exception of type out_of_range is thrown. Notice that the first element has a position of 0 (not 1). Member type size_type is an alias of the unsigned integral type size_t.

Return value

The element at the specified position in the array.

If the array object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference.

Member types reference and const_reference are the reference types to the elements of the array (see array member types).

#include <iostream>
#include <array>

int main(int argc, char const *argv[])
{
    std::array <int, 3> arr= {2,3,4};
    std::cout << arr.at(0) << std::endl; //2
    return 0;
}

assign and print value

#include <iostream>
#include <array>

int main(int argc, char const *argv[])
{
    std::array <int, 10> arr;
    for (int i = 0; i < 10; i++)
    {
        arr.at(i) = i+1;
    }

    //print with array.at() function
    std::cout<<"print with array.at() function"<<std::endl;
    for (int i = 0; i < 10; i++)
    {
        std::cout<<arr.at(i)<<" ";
    }
    std::cout<<std::endl;

    //print with auto
    std::cout<<"print with auto"<<std::endl;
    for (auto x:arr){
        std::cout<< x <<" ";
    }
    std::cout<<std::endl;

    //print with decltype
    std::cout<<"print with decltype"<<std::endl;
    for (decltype(arr.at(0)) x:arr){
        std::cout<< x <<" ";
    }
    std::cout<<std::endl;

    return 0;
}
iMac-52:a apple$ clang++ -std=c++11 -g -o a.out main.cpp 
iMac-52:a apple$ ./a.out
print with array.at() function
1 2 3 4 5 6 7 8 9 10 
print with auto
1 2 3 4 5 6 7 8 9 10 
print with decltype
1 2 3 4 5 6 7 8 9 10

results matching ""

    No results matching ""