Reputation: 55
My understanding is that you can access the data in a std::vector using pointers. For example:
char *ptr;
std::vector<char> v1 {'A', 'B', 'C'};
ptr = &v1[0]
if (*(ptr+1) == 'B')
std::cout << "Addressing via pointer works\n";
How about loading a std::vector directly? For example:
std::vector<char> v2;
v2.reserve(3); // allocate memory in the vector
ptr = &v2[0]
*ptr = 'A';
*(ptr+1) = 'B';
*(ptr+2) = 'C';
if (v2[1] == 'B')
std::cout << "Data is in vector buffer!\n";
but
if (!v2.size())
std::cout << "But the vector doesn't know about it!\n";
My question: Is there any way to tell the v2 vector that its internal memory buffer is loaded with data? This would be useful when you want to use a std::vector to hold data that is sourced from a file stream.
I look forward to your comments.
Upvotes: 0
Views: 282
Reputation: 238291
Is there any way to tell the v2 vector that its internal memory buffer is loaded with data?
No.
The behaviour of your second example is undefined.
This would be useful when you want to use a std::vector to hold data that is sourced from a file stream.
You can read a file into vector like this:
std::vector<char> v3(count);
ifs.read(v3.data(), count);
Or like this:
using It = std::istreambuf_iterator<char>;
std::vector<char> v4(It{ifs}, It{});
Upvotes: 1