C++ emplace_back

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_backput it (actually copied) vectorin.

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_backwith push_backless than copying process up, so it also has a higher efficiency:

The int*type into other variables vector, using emplace_backthe speed of about push_backof 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

push_back vs emplace_back

cpp-code-snippets/vector_emplace_back_object.cpp

cpp-code-snippets/vector_emplace_back_push_back.cpp

发布了100 篇原创文章 · 获赞 9 · 访问量 6万+

Guess you like

Origin blog.csdn.net/keineahnung2345/article/details/104089241