vector 중push백과 emplace백의 차이

2729 단어 STL

1. 두 가지 차이


오른쪽 값 인용, 구조 함수 이동, 복제 연산자 이동 전에 보통push백()이 용기에 오른쪽 원소(임시 대상)를 추가할 때 먼저 구조 함수를 호출하여 임시 대상을 구성한 다음에 복사 구조 함수를 호출하여 이 임시 대상을 용기에 넣어야 한다.원래의 임시 변수 방출.이렇게 초래된 문제는 임시 변수 신청의 자원이 낭비되는 것이다.오른쪽 값 인용을 도입하고 구조 함수를 옮긴 후pushback () 오른쪽 값일 때 구조 함수와 전이 구조 함수를 호출합니다.이 위에 더 최적화된 공간이 있는데 바로 emplace 를 사용합니다.back, 용기 끝부분에 원소를 추가합니다. 이 원소는 제자리 구조입니다. 복사 구조와 전이 구조를 터치할 필요가 없습니다.또한 호출 형식이 더욱 간결하여 매개 변수에 따라 임시 대상의 구성원을 직접 초기화한다. 

2. 코드 실례

#include   
#include   
#include   

struct President  
{  
    std::string name;  
    std::string country;  
    int year;  
    
    // 
    President(std::string p_name, std::string p_country, int p_year)  
        : name(std::move(p_name)), country(std::move(p_country)), year(p_year)  
    {  
        std::cout << "I am being constructed.
"; } // President(const President& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year) { std::cout << "I am being copy constructed.
"; } // President(President&& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year) { std::cout << "I am being moved.
"; } // President& operator=(const President& other); }; int main() { std::vector elections; std::cout << "emplace_back:
"; elections.emplace_back("Nelson Mandela", "South Africa", 1994); // std::vector reElections; std::cout << "
push_back:
"; reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936)); std::cout << "
Contents:
"; for (President const& president: elections) { std::cout << president.name << " was elected president of " << president.country << " in " << president.year << ".
"; } for (President const& president: reElections) { std::cout << president.name << " was re-elected president of " << president.country << " in " << president.year << ".
"; } }
출력:
emplace_back:
I am being constructed.

push_back:
I am being constructed.
I am being moved.

Contents:
Nelson Mandela was elected president of South Africa in 1994.
참조:https://blog.csdn.net/xiaolewennofollow/article/details/52559364

좋은 웹페이지 즐겨찾기