S-K'
S-K'

Reputation: 3209

Extract uint8_t* subset from a vector<uint8_t>

I have a vector<uint8_t>, and I'm interfacing with an api that expects a uint8_t* data, size_t size. I need to provide the api with a subset of my vector, in my current solution I create a subset by using the vector constructor, and then I pass the data() of this new vector to the api:

vector<uint8_t> subset(bytes.begin() + offset, bytes.begin() + offset + size);
api(subset.data(), subset.size());

This works fine in the majority of cases, but it is running out of memory on constrained devices. Is there a more efficient way to extract a uint8_t* subset from a vector<uint8_t>?

Upvotes: 1

Views: 317

Answers (2)

user9559196
user9559196

Reputation: 157

I Think you dont need to make a subset, pass vector's first element and size to want to take out of it. Make sure this size is less than equal to bytes.size()

api(&bytes[0],size);

Upvotes: 0

john
john

Reputation: 87997

Yes, just combine the two but with data instead of begin.

api(bytes.data() + offset, size);

Using subscript and address-of operators also works

api(&bytes[offset], size);

Upvotes: 5

Related Questions