简体   繁体   中英

Int array to C++ container

I've got some data coming from a source in a int array. Essentially..

// C interface
typedef struct {
    int payload[1024];
    int id;
} tData;

// C++ interface
void MyModule::HandleData(tData *data){
   this->DoUsefulThingsWithData(data->payload);
}

This is from a C file written in a functional style. I now want to take this data and use it in my C++ module. Do I pack it all into a vector, or should I just continue to use the data as is? If I use a vector, I don't have to pass a size to DoUsefulThingsWithData , but is it worth the overhead? Also I don't exactly know when that data will become irrelevant (scope or freed) so I should copy it into something before continuing to use. What's the best container for this with the lowest overhead on performance (copy) and size? Note: I am in c++ 98

Do I pack it all into a vector?

Yes:

std::vector payload(tData.payload, tData.payload + sizeof(tData.playload));

If I use a vector, I don't have to pass a size to DoUsefulThingsWithData.

Just use vector 's data() member function:

this->DoUsefulThingsWithData(payload.data());

... so I should copy it into something before continuing to use.

If I use a vector ... but is it worth the overhead?

Overhead compared to what? std::vector is the ideal standard container for this use case.

That said, it's probably best to let DoUsefulThingsWithData implementation choose how to store the data if that is what the function does.

If I use a vector, I don't have to pass a size to DoUsefulThingsWithData

You also don't need to pass the size if you use reference to array as the argument type. I recommend this.

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