
- The C Standard Library
- The C Standard Library
- The C++ Standard Library
- C++ Library - Home
- C++ Library - <fstream>
- C++ Library - <iomanip>
- C++ Library - <ios>
- C++ Library - <iosfwd>
- C++ Library - <iostream>
- C++ Library - <istream>
- C++ Library - <ostream>
- C++ Library - <sstream>
- C++ Library - <streambuf>
- C++ Library - <atomic>
- C++ Library - <complex>
- C++ Library - <exception>
- C++ Library - <functional>
- C++ Library - <limits>
- C++ Library - <locale>
- C++ Library - <memory>
- C++ Library - <new>
- C++ Library - <numeric>
- C++ Library - <regex>
- C++ Library - <stdexcept>
- C++ Library - <string>
- C++ Library - <thread>
- C++ Library - <tuple>
- C++ Library - <typeinfo>
- C++ Library - <utility>
- C++ Library - <valarray>
- The C++ STL Library
- C++ Library - <array>
- C++ Library - <bitset>
- C++ Library - <deque>
- C++ Library - <forward_list>
- C++ Library - <list>
- C++ Library - <map>
- C++ Library - <queue>
- C++ Library - <set>
- C++ Library - <stack>
- C++ Library - <unordered_map>
- C++ Library - <unordered_set>
- C++ Library - <vector>
- C++ Library - <algorithm>
- C++ Library - <iterator>
- C++ Programming Resources
- C++ Programming Tutorial
- C++ Useful Resources
- C++ Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Array Library - at() Function
Description
The C++ function std::array::at() returns a reference to the element present at location N in given array container.
Declaration
Following is the declaration for std::array::at() function form std::array header.
reference at(size_type n); cont_referece at(size_t n) const;
Parameters
N − index of an element in the array.
Return Value
Returns a element present at index N in given array if N is valid index otherwise throws out_of_range exception.
If array object is const-qualified method returns const reference otherwise it returns reference.
Exceptions
This member function throws out_of_range expception if value of N is not valid array index.
Time complexity
Constant i.e. O(1)
Example
In below example step-1 prints array contents without exception. Step-2 shows exception handling using try-catch block.
#include <iostream> #include <array> #include <stdexcept> using namespace std; int main(void) { array<int, 5> arr = {10, 20, 30, 40, 50}; size_t i; /* print array contents */ for (i = 0; i < 5; ++i) cout << arr.at(i) << " "; cout << endl; /* generate out_of_range exception. */ try { arr.at(10); } catch(out_of_range e) { cout << "out_of_range expcepiton caught for " << e.what() << endl; } return 0; }
Let us compile and run the above program, this will produce the following result −
10 20 30 40 50 out_of_range expcepiton caught for array::at: __n (which is 10) >= _Nm (which is 5)