简体   繁体   中英

Can you pass pointers to iterators of a std::vector

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.

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