Sign in to follow this  
Timberl

Best way to store variable-length array of doubles in C++ (need v.fast read/write)?

Recommended Posts

This is to store audio-sample data. I'm not sure the best way to go about it in C++. I currently have something like typedef double SamplePiece; struct Sample{ long length; SamplePiece* data; } The structure is used very intensively - with potentially many more than 100 channels - each going at minumum 44kb/s and with effects etc. being calculated over them (thus the reason I'm scared of incurring overhead on the access of them). I gather that in C++ for text it's generally best to use the std 'string' class. I'm looking for something similar for doubles as std 'string' is for chars. I had the impression that vector might be a bad choice because of the overhead it incurs. is this fear unwarranted? I have little experience using them What would be best in this scenario of using a struct (similar to the above), a vector of doubles or something else?

Share this post


Link to post
Share on other sites
A vector of double is fine. It internally boils down pretty much to your Sample struct - except with code actually written to manage it. There is no 'overhead', except as for what little code ensures your data and data structure are well-formed. [smile]

If you do know the amount of data you're going to read in advance, a simple call to std::vector::reserve() will preallocate the memory for you. Then you can go ahead and insert elements in the vector without it needing reallocation.

If you do want to directly copy the data in the vector, it is possible too, though you will pay a slight cost, since std::vector::resize(), which does actually modify the number of elements in a vector (as opposed as just doing memory allocation), will default-construct the elements in the vector (i.e. here it'll set all the values to zero), which is unnecessary since you're going to overwrite them anyway. Doing so allows you, however, to use the vector as a plain array (by passing the address of its first element: &vec[0]) with functions that take a pointer, such as std::ifstream::read(), allowing you to 'optimize' the file accesses themselves (though std::ifstream are buffered).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this