简体   繁体   中英

C++ create a char* iterator

I like to write container agnostic code that uses std methods like std::distance() or std::advance() in my code. This is useful for deserialization where I can pass in buffer objects of different types (network stream, byte stream, ...).

How can I convert char* or uint8_t* pointers to an iterator? Copying the data to a buffer is not an option.

One option I have in mind is to use a custom allocator with std::string but I'd prefer a more ready made solution if available.
Any suggestions?

Nevermind. Those pointers work as iterators anyway because they implement the basic functionality.

There are several types of iterators, specified by what properties they have (functionality they support) - there is a nice overview here http://www.cplusplus.com/reference/iterator/

Random access iterators require to implement all the iterator functionality seen in that table.

Raw pointers do in fact support all the operations and are therefore random access operators iterators and can be used for all STL algorithms and containers. Also discussed here Can raw pointers be used instead of iterators with STL algorithms for containers with linear storage? .

Although not necessary, it might still be useful to implement an iterator wrapper for your pointers - this is also discussed in the answers to the question above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM