Inserts a new element at the end of the vector, right after its current last element. This new element is constructed in place using args as the arguments for its constructor.
The element is constructed in-place by calling allocator_traits::construct with args forwarded. A similar member function exists, push_back, which either copies or moves an existing object into the container.
可以看出,emplace 用于直接传入constructor 需要的参数,inplace地构造对象。而 push_back 则需要将对象 copy or move 入容器。
classTest{public:int a;explicitTest(inta){this->a= a; cout <<"constructor: a = "<< a << endl;}Test(constTest&that){ cout <<"copy constructor, a = "<<that.a<< endl;this->a=that.a;}Test(Test&&that)noexcept{ cout <<"move constructor, a = "<<that.a<< endl;this->a=that.a;}};intmain(){ Test t1{3}; vector<Test> v;v.emplace_back(2);// 即使构造函数是 explicit,仍然可以隐式调用,只call一次constructor, no copy,no movev.emplace_back(Test(2));// call 一次 constructor,一次 movev.push_back(2);// 如果构造函数 Test(int a) 声明为 explicit,则报错,因为无法隐式调用v.push_back(Test(2));// call 一次 constructor,一次movev.emplace_back(2.5);// no warning, create object of Test with a == 2v.push_back(2.5);// 如果构造函数非explicit,会有warning,"implicit conversion from 'double' to 'int'"// 如果构造函数explicit,同样会报错。return0;}
在Java中,如果我判断 if (a < 0x80000000),this is equivalent to if (a < Integer.MIN_VALUE) and if (a < -2147483648)。但在 c++ 中,0x80000000 却被当做了 usigned int,等于 2147483648,如果需要实现和Java中一样的效果,需要手动转换为int:(int)0x80000000。
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);
// or
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>(){
@Override
public int compare(Integer a, Integer b) {
return Integer.compare(b, a);
}
});
auto comp = [](int a, int b){ return b - a; };
priority_queue<int, vector<int>, decltype(comp)> pq(comp);
z ==> const unordered_map<int, int>&;
int val = 0;
auto it = z.find(5);
if (it != z.end()) val = it->second;