Harvey Harvey - 11 months ago 58
C++ Question

Can I access the end from only an iterator?

I have an iterator into a QByteArray which is passed to a function as:

MyData getNext(const QByteArray::const_iterator &it) {
// calculate N
if(end_of_array >= it + N)
// process N bytes

I need to know if there are at least N bytes left in the array. Can I access the array object or the end from this passed iterator?

Answer Source

Since QByteArray::const_iterator is just a typedef from const char * , it is impossible to retrieve the original QByteArray object without further context.

You cannot reconstruct an end() iterator either for exactly the same reason, at least without deeper knowledge of the data contained in the object. For example, if the data in a QByteArray is a null-terminated string you could look for \0, for example using strlen. Do note that QByteaArray::end() will point beyond that, since the null-terminator is part of the data it contains.

Obviously it is better to either pass a const reference to the QByteArray object along with the iterator (or an end iterator).