简体   繁体   English

C ++创建一个char *迭代器

[英]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. 我喜欢编写在代码中使用std std::distance()std::advance()类的std方法的容器不可知代码。 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? 如何将char*uint8_t*指针转换为迭代器? 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. 我想到的一个选择是使用带有std::string的自定义分配器,但我希望有一个更现成的解决方案(如果有)。
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/ 迭代器有几种类型,由它们具有的属性(它们支持的功能)指定-这里有一个很好的概述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. 原始指针实际上确实支持所有操作,因此是随机访问 运算符的 迭代器,可用于所有STL算法和容器。 Also discussed here Can raw pointers be used instead of iterators with STL algorithms for containers with linear storage? 这里还讨论了对于具有线性存储的容器,可以使用原始指针代替STL算法的迭代器吗? .

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. 尽管不是必需的,但为指针实现迭代器包装可能仍然有用-上面问题的答案中也对此进行了讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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