问题
Is there a way to encapsulate std::map
within a user-defined class, allowing iteration, but not allowing direct access to the key?
I would like to manipulate the key upon insertion and I want to force all access to elements through a user-defined method (as the key will need to be modified).
I think the problem is allowing iterating over the map, whilst preventing the user from accessing the key via the iterator.
回答1:
Do not expose iterators. Expose a for_each
function that passes each element to the user-provided (lambda) function.
Alternatively, use a transform iterator.
来源:https://stackoverflow.com/questions/51862149/encapsulate-stdmap-to-allow-iterating-but-no-direct-key-access