0

what is difference between emplace() and push() ?please explain with example

i have search in google not feeling confident i have use it in stack and they do same job of inserting so what is benifits of using 1 over another

29th Jun 2018, 3:42 AM
Bahubali
Bahubali - avatar
4 Antworten
+ 5
The push() function adds a new element to the container. It accepts a variable of the type of the element and adds it. The emplace() function accepts the arguments required for creating a new object and adds a newly created object to your container. Thus, the constructor is called to create a new object for addition. Eg : struct Point { int X,Y,; Point(int x=0,int y=0,int z=0): X(x),Y(y),Z(z) { std::cout<<"Ctor Called\n";} }; int main() { std::stack<Point> shape; Point p{2,2}; shape.push(p); shape.emplace(3,3,3); shape.emplace(4,4); }
29th Jun 2018, 6:50 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
push() inserts element at index 0 emplace() is used to insert element at specific index
29th Jun 2018, 4:09 AM
‎ ‏‏‎Anonymous Guy
+ 1
thank u
29th Jun 2018, 7:44 AM
Bahubali
Bahubali - avatar
0
include <iostream> #include <stack> #include <string> // std::string int main () { std::stack<std::string> mystack; mystack.push("First sentence"); mystack.push ("Second sentence"); std::cout << "mystack contains:\n"; while (!mystack.empty()) { std::cout << mystack.top() <<'\n'; mystack.pop(); } return 0; } replace push by emplace they work same
29th Jun 2018, 4:26 AM
Bahubali
Bahubali - avatar