I came across the following code and it raised some questions in my head
std::vector<unsigned char> buf(bytes.constData(), bytes.constData() + bytes.size());
where bytes is QByteArray
and bytes.constData()
returns const char*
I went over the constructor of the vector here and the only constructor that I think fits for this description is
vector (InputIterator first, InputIterator last,
const allocator_type& alloc = allocator_type());
Now my question is:
1-Is it possible to pass a pointer to an iterator of a vector ? and why is it bytes.constData() + bytes.size()
? Does this make a copy for instance if we later made changes to bytes would it affect buf ?
"An iterator of a vector" is misguided here: the vector constructor in question is a template and accepts any iterator. That's the whole point -- you can construct the container from any iterable range.
And pointers are indeed iterators. In fact, the entire concept of iterators is basically a generalization of the notion of a "pointer".
The vector constructor copies the data from the input range, so later changes to
bytes
will not affect the vector.