79119548

Date: 2024-10-23 20:08:47
Score: 0.5
Natty:
Report link

Yea, Here are some basic points that explain differe nce between the push () and emplace () methods of queue data structure in C++.

1. Push ( ) Push of std::queue requires an existing ( either temporary or not ) object of T type as an argument to add in queue.

2. Emplace( ) Emplace ( ) of std::queue does not require an existing object of T type as argument. Instead the arguments requiring by constructors of T object to declare T type object are required by emplace () directly, as its arguments.

  1. Push( ) Since an existing object ( either temporary or non-temporary ) is passed as argument in push( ) method so to add a new element in std::queue it requires copying or moving of that existing object to create a new object at index next to last (back) element of std::queue. It means to use push ( ) we have to create an object for two times. One before using push( ) , to pass as parameter.And second inside push( ) method, in order to create similiar object at index next to last element of std::queue . Sometimes receiving object can be moved to new place instead of copying it.

    #include #include using namespace std; int main( ) { queue q; string st= "xyz" ; // 1st creation of string object q.push( st) ; // during push( ) 2nd creation of string object }

  2. Emplace( ) Since parameters for creation of T type object are passed as arguments of Emplace ( ) ,I mean we don't need to initialize object before call of Emplace instead initilization occurs only one time ,in during emplace ( ) method to make an object the element of std::queue , so no need to move or copy an object.

    #include #include using namespace std; int main( ) { queue q; q.push( (const char * )("xyz") ) ; // during push( ) 1st creation of string object }

  1. Push( ) Due to to 2 times creation of object in it, not in move case rather in copy case, the space complexity of whole the program overall increases.

2.Emplace( ) Program's overall space complexity is less than the case of push ( ) due to just one time creation of object.

These points explain about the core differences between push() and emplace() methods so emplace is preferable in the case when object is not created already.

Reasons:
  • Long answer (-1):
  • No code block (0.5):
  • Low reputation (1):
Posted by: Umer Farooq