So I am trying to load a binary file into a Vector, so I can use it like a Buffer.
ifstream binaryFile;
vector<unsigned char> fileBuffer(istreambuf_iterator<char>(binaryFile), {});
vector<unsigned char>::iterator fileIter = fileBuffer.begin();
Now my question is, if I use the fileIter
variable, can I access all the elements in the fileBuffer
vector ?
I want to know, because I need to edit the contents of the fileBuffer
only at certain Positions, that is why I am working with iterators int the first place.
Simplified, I want to know, if I can edit the elements in the vector fileBuffer
, if I edit the fileIter
with code like *(fileIter + 2) = 'a';
I have researched this Topic but I have not yet found an answer.
The standard class template std::vector has a random access iterator. So you can use it the same way as a pointer. For example
fileIter[10] = 'A';
or
fileIter += 10;
and so on.
Here is a demonstrative program.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5 };
for ( const auto &item : v ) std::cout << item << ' ';
std::cout << '\n';
auto it = v.begin();
it[1] = -it[1];
for ( const auto &item : v ) std::cout << item << ' ';
std::cout << '\n';
it += 2;
*it *= 10;
for ( const auto &item : v ) std::cout << item << ' ';
std::cout << '\n';
return 0;
}
Its output is
1 2 3 4 5
1 -2 3 4 5
1 -2 30 4 5
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.