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
4 Respostas
+ 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);
}
+ 3
push() inserts element at index 0
emplace() is used to insert element at specific index
+ 1
thank u
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