Files
json/docs/mkdocs/docs/api/basic_json_view/back.md
T
Niels Lohmann c8b380769c Index arrays without subtrees directly
operator[](idx), at(idx) and back() skipped the elements of an array one
after the other, whatever they were. In an array none of whose elements is
an array or object (numbers, strings, booleans, null) the elements are
adjacent nodes, which the array node's own sizes tell: its subtree has
exactly one node more than it has elements. Such an element is now the
node idx after the array node; any other array is walked as before.

Reading r[i] for every i of an array of 3000 integers:
  Apple M1: 28.8 M instructions, 3.1 ms -> 0.1 M instructions, 4 us
  Linux x86-64 Ir (whole run), GCC 13 / Clang 18: 84.1 M -> 3.1 M / 75.0 M -> 3.0 M
Arrays that contain arrays are unchanged.

Belongs to the PR "json_view: read-side speedups".

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-22 09:30:12 +02:00

2.2 KiB

nlohmann::basic_json_view::back

basic_json_view back() const;

Returns the last element of an array, the last member value of an object, or the value itself if it is primitive (as for BasicJsonType::back(), a primitive value is a range of one element).

Return value

The last element or member value. For a primitive value (number, string, boolean), the value itself.

Exception safety

Strong guarantee: there are no changes to the view or the document it refers to.

Exceptions

Throws invalid_iterator.214 if the view is null or discarded, or if it is an empty array or object.

This exception does not carry a JSON_DIAGNOSTICS path: the view has no BasicJsonType value to point at, so the exception is created without one, even if BasicJsonType was built with JSON_DIAGNOSTICS enabled.

Complexity

Linear in the size of the array or object: unlike front(), which only ever looks at the first element, back() has to walk every element to find where they end, since elements are not a fixed size in the index. Constant for an array none of whose elements is an array or object, since the elements are then adjacent in the index.

Notes

Unlike BasicJsonType::back(), which has undefined behavior for an empty array or object, back() throws invalid_iterator.214 for an empty array, an empty object, a null value, or a discarded view.

Examples

??? example

The example below reads only the final status of a build log with `back()`. Even though `back()` is linear in
the number of events (unlike [`front()`](front.md), which is constant), it still avoids building a
`BasicJsonType` value for the events that are not needed.

```cpp
--8<-- "examples/basic_json_view__back.cpp"
```

Output:

```json
--8<-- "examples/basic_json_view__back.output"
```

See also

Version history

  • Added in version 3.13.0.