Returns a const reference to the element at specified location idx, with bounds checking.
- Parameters
-
[in] | idx | index of the element to access |
- Returns
- const reference to the element at index idx
- Exceptions
-
type_error.304 | if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below. |
out_of_range.401 | if the index idx is out of range of the array; that is, idx >= size() . See example below. |
- Exception safety
- Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
- Complexity
- Constant.
- Since
- version 1.0.0
- Example
- The example below shows how array elements can be read using
at()
. It also demonstrates the different exceptions that can be thrown.
2 #include <nlohmann/json.hpp>
9 const json array = {
"first",
"2nd",
"third",
"fourth"};
12 std::cout <<
array.
at(2) <<
'\n';
19 const json str =
"I am a string";
20 std::cout << str.at(0) <<
'\n';
24 std::cout << e.what() <<
'\n';
31 std::cout <<
array.
at(5) <<
'\n';
35 std::cout << e.what() <<
'\n';
Output (play with this example online): "third"
[json.exception.type_error.304] cannot use at() with string
[json.exception.out_of_range.401] array index 5 is out of range
The <a href= https://github.com/nlohmann/json/blob/develop/doc/examples/ at__size_type_const.cpp>example code above can be translated withg++ -std=c++11 -Isingle_include doc/examples/
at__size_type_const.cpp -o
at__size_type_const
Definition at line 17571 of file json.hpp.