c++ - Working with structure objects -
i have logic looks below (not actual code):
structureelement x; in 1 1000 x.elem1 = 20; x.elem2 = 30; push(x std::vector) end
my knowledge x allocated memory once , existing values overwritten every iteration. also, 'x' pushed vector not affected subsequent iterations of pushing modified 'x'.
am right in observations?
is above optimal? want keep memory consumption minimal , not prefer using new. missing not using new?
also, pass vector , recieve reference it method.
and, if read vector elements back, right?
structure element xx = myvector.begin() print xx.elem1 print xx.elem2
any optimizations or different ideas welcome.
am right in observations?
yes, if vector std::vector<structureelement>
, in case keeps own copies if pushed in.
is above optimal?
it sub-optimal because results in many re-allocations of vector's underlying data buffer, plus unnecessary assignments , copies. compiler may optimize of assignments , copies away, there no reason, example, re-set elements of x
in loop.
you can simplify this:
std:vector<structureelement> v(1000, structureelement{20, 30});
this creates size-1000 vector containing copies of structureelement
desired values, seem trying in pseudo-code.
to read elements back, have options. range based for-loop if want iterate on elements:
for (const auto& e: v): std::cout << e.elem1 << " " << e.elem2 << std::endl;
using iterators,
for (auto = begin(v); != end(v); ++it) std::cout << it->elem1 << it->elem2 << std::endl;
or, pass ranges in algorithms
std::transform(begin(v), end(v), ....);
Comments
Post a Comment