Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector adding elements efficiently

Suppose I have the following code:

#include <iostream>
#include <vector>
using namespace std;

class X {
public:
  int x[1000];
  X(int y) { for (int i = 0; i < 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 I understand correctly, in my code, I am allocating memory on the stack for x0, x1 and x2, then copying those contents onto memory allocated for me by vector. Furthermore, as far as I understand, move semantics can't help here because it's not exactly like X is holding a pointer to resource located somewhere else.

Is it possible for me to directly call the constructor on the raw memory block allocated for me by vector? If not, what would be the proper way to handle situations like these?

like image 235
math4tots Avatar asked Sep 01 '25 17:09

math4tots


2 Answers

You need to use C++11's emplace_back.

http://en.cppreference.com/w/cpp/container/vector/emplace_back

Also, if you're concerned about excess copies/moves, try starting with v.reserve(3).

like image 62
StilesCrisis Avatar answered Sep 04 '25 06:09

StilesCrisis


You can also use std::ref or boost::ref if available and store a reference of the object in the vector, thus avoiding the copy.

#include <iostream>
#include <vector>
#include <functional>
using namespace std;

class X {
public:
  int x[1000];
  X(int y) { for (int i = 0; i < 1000; i++) x[i] = y; }
};

int main() {
  std::vector<std::reference_wrapper<X> > v;
  X x0(0);
  X x1(1);
  X x2(2);


  v.push_back(std::ref(x0));
  v.push_back(std::ref(x1));
  v.push_back(std::ref(x2));
  cout << v[2].get().x[33] << endl;
  return 0;
}
like image 44
andre Avatar answered Sep 04 '25 05:09

andre