Say I have a custom container class that stores data in a map:
class Container
{
public:
void add(int key, std::string value) { _data.emplace(key, std::move(value)); }
private:
std::map<int, std::string> _data;
};
I want to provide an interface to access the values (not the keys) of the map. The ranges library provides std::views::values
to give me a range of the map's values:
auto values() { return std::views::values(_data); }
Usage:
Container c;
c.add(1, "a");
c.add(3, "b");
c.add(2, "c");
for (auto &value : c.values())
std::cout << value << " "; // Prints "a c b"
But since I want to treat my class as a container, I want to have begin()
and end()
iterators. Can I do this?
auto begin() { return std::ranges::begin(values()); }
auto end() { return std::ranges::end(values()); }
Here I'm calling values()
to get the range to the map's values, and getting an iterator to the beginning of the range (or the sentinel end iterator). But the range itself goes out of scope and is destroyed. Is the iterator itself still valid?
From this example, it seems like the iterator is valid. But is that guaranteed by the standard, either for std::views:values
specifically or for views in general?