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

Started by
1 comment, last by Fruny 19 years, 6 months ago
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?
Advertisement
A vector<double> would be best. The STL is very well designed and runs very quickly. Your fear that it has too much overhead is indeed unwarranted.
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).
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement