Views of Container Types

Viewed 111

According to http://eel.is/c++draft/range.view#concept:view , a view of a range is satisfied only when the range allows constant time move construction, move assignment, and destruction.

However, I'm wondering how a container item, such as std::map, can be converted to a viewable_range. The time complexity of the underlying red-black tree is O(log n) for typical operations rather than O(1).

The theory at: http://eel.is/c++draft/range.refinements#concept:viewable_range states that the viewable_­range concept specifies the requirements of a range type that can be converted to a view safely. [The term 'safely' is a little ambiguous to understand]

To put my question in another way, I'm wondering why does code like this compile without errors, wherein table_entries is considered as viewable_range but in theory it should not be since the time complexity is not O(1).

#include <map>
#include <algorithm>
#include <ranges>

auto main() -> int {

    std::map<int, int> table_entries;
    auto vals = std::ranges::min(table_entries | std::views::values);

    return 0;
}
1 Answers

The confusion appears to be arising from this line:

The view concept specifies the requirements of a range type that has constant time move construction, move assignment, and destruction; ...

This doesn't mean that the underlying range that the view is constructed from needs to support constant time operations. It's only the view itself that needs to support constant time operations.


Note that the container table_entries is not a view itself (for the reasons you mentioned). However, table_entries | std::views::values is a view as it generates each value in the map, lazily and on demand.

Here's another example:

table_entries;                  // not a view
std::views::all(table_entries); // is a view
Related