C++ emplace_back
emplace_back
Before C ++ 11, we only have std::vector::push_back
, so we have to create a temporary object, and then call push_back
put it (actually copied) vector
in.
C ++ 11 introduced std::vector::emplace_back
, it can take arguments constructor of its elements as input, then in-place to build a container to create objects in the specified location. It allows us can avoid temporary object, the syntax is more concise:
#include <iostream>
#include <vector>
class Rectangle{
public:
Rectangle(int h, int w): height(h), width(w){
area = height * width;
};
int get_area(){
return area;
}
private:
int area;
int height;
int width;
};
int main(){
std::vector<Rectangle> rects;
rects.push_back(Rectangle(10,20));
rects.emplace_back(20,30);
return 0;
}
Full code in CPP-code-Snippets / vector_emplace_back_object.cpp .
Because emplace_back
with push_back
less than copying process up, so it also has a higher efficiency:
The int*
type into other variables vector
, using emplace_back
the speed of about push_back
of about twice. Reference code:
CPP-code-Snippets / vector_emplace_back_push_back.cpp .
Reference Links
std::vector<T,Allocator>::emplace_back
vector::emplace_back in C++ STL