Re: Using a std::vector as a variable-length receive buffer
Frank Birbacher wrote:
:: Hi!
::
:: irotas schrieb:
::: According to those pages, 'reserve()' is O(1), and 'resize()' is
::: O(N). Therefore, if 'reserve()' will suffice here, it is
::: preferable.
:::
::: Basically what the question boils down to is whether or not
::: 'reserve()' allocates its memory at the address that will point
::: to the 0'th element after 'reserve()' returns.
::
:: Basically the point is you must not access positions in the vector
:: which are not within its size (!) limits. That is you must use
:: resize().
::
:: vector<int> v;
:: v.reserve(10);
:: v[0] = 10; //not allowed
::
:: Well, if you resize the vector to make it smaller it is allowed to
:: hold on to the current memory (and not release any). So if your
:: messages are roughly the same size each time you might as well
:: just use resize to enlarge your vector:
::
:: size_t incoming = ...;
:: if(buffer.size() < incoming)
:: buffer.resize(incoming);
::
:: This way you will have reduced timing for resize in the scope of
:: the wohle application. But when I would read the code using the
:: buffer I would ask myself why buffer.size() is not the correct
:: message length.
::
:: If you don't like that then I guess you will have to use a plain
:: array. You can put that into a vector like class which gives you
:: access to uninitialised elements. (Initialising the elements is
:: what takes resize so long).
It all depends on what you mean by "so long". :-)
How "long" does it take to fill a vector<char> with a few thousand
chars? Compared to the socket ops it is supposed to interface with?
Bo Persson
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]