c++ - Making a vector more efficient while adding elements -
c++ - Making a vector more efficient while adding elements -
i thinking of making vector info construction more efficient.
suppose generic info type t...then while adding new element vector, current std::vector reallocate whole new memory chunk of n+1 elements.
what want do...
i wrote little programme :
#include<iostream> using namespace std; int main () { int *i,*j; i=new int; cout<<i; delete i; j=new int ; cout<<j; delete j; homecoming 0; }
both memory locations same...
now thinking first allocate memory generic info type :
t *temp=new t;
now compare memory address of temp address of lastly element of vector....if differ sizeof (t)
add together new element there itself....else way std::vector
it....
so reduces cost of copying elements...if info big can create important difference......!!
pls tell me if on right track...
i understand thought as
if new
gives me address contiguous memory held myvector
object, utilize without reallocating.
yes, indeed work in theory. however, in practice, it's impossible obtain such contiguous address, because allocator store internal info @ start of block allocates (such size, or pointer next block, or whatever).
exact details depend on allocator used standard library (and eventuall os), here's illustration of typical behaviour. phone call new t
sizeof(t)
16 (for example). operator new
calls malloc
internally, calls os's allocation function. function allocates 20 bytes of memory @ address x
. stores "16" in first 4 bytes @ x
, , returns address x + 4
malloc
, in turn returns operator new
, application. there's no way you'll ever contiguous memory.
c++ vector processing-efficiency
Comments
Post a Comment