memory management - C++ vector adding elements efficiently -
suppose have following code:
#include <iostream> #include <vector> using namespace std; class x { public: int x[1000]; x(int y) { (int = 0; < 1000; i++) x[i] = y; } }; int main() { vector<x> v; x x0(0); x x1(1); x x2(2); v.push_back(x0); v.push_back(x1); v.push_back(x2); cout << v[2].x[33] << endl; return 0; }
if understand correctly, in code, allocating memory on stack x0
, x1
, x2
, copying contents onto memory allocated me vector
. furthermore, far understand, move semantics can't here because it's not x
holding pointer resource located somewhere else.
is possible me directly call constructor on raw memory block allocated me vector
? if not, proper way handle situations these?
you need use c++11's emplace_back
.
http://en.cppreference.com/w/cpp/container/vector/emplace_back
also, if you're concerned excess copies/moves, try starting v.reserve(3)
.
Comments
Post a Comment