Vector emplace back struct in C++
1 min readMay 6, 2021
The point of using
emplace_back
is to avoid creating a temporary object, which is then copied (or moved) to the destination. While it is also possible to create a temporary object, then pass that toemplace_back
, it defeats (at least most of) the purpose. What you want to do is pass individual arguments, then letemplace_back
invoke the ctor with those arguments to create the object in place. From [1]
The code is for a two pointer problem
const int INF = 1e9;
struct Query{
int id, prefered, minSize;
// Line 1
Query(int id, int prefered, int minSize): id{id}, prefered{prefered}, minSize{minSize}{};
bool operator< (const Query& b) {
return minSize < b.minSize;
}
};
class Solution {
public:
vector<int> closestRoom(vector<vector<int>>& rooms, vector<vector<int>>& queries) {
const int n = queries.size(), m = rooms.size();
vector<int> ret(n, -1);
vector<Query> q;
q.reserve(n);
for (int i = 0; i < n; ++i){
// remove Line 1 will get error here.
q.emplace_back(i, queries[i][0], queries[i][1]);
}
sort(q.begin(), q.end());
sort(rooms.begin(), rooms.end(), [](const vector<int> &a, const vector<int> &b) {
return a[1] < b[1];
});
set<int> S={-INF, INF};
int i = m;
for (int j = n -1; j >= 0; --j) {
auto minSize = q[j].minSize;
while (i - 1 >= 0 and rooms[i-1][1] >= minSize ) {
S.insert(rooms[i-1][0]);
--i;
}
auto prefered = q[j].prefered;
auto it = S.upper_bound(prefered);
auto thisRet = abs(*it - prefered) < abs(*prev(it) - prefered) ? *it : *(prev(it));
if (abs(thisRet) != INF) ret[q[j].id] = thisRet;
}
return ret;
}
};
Reference
[1] https://stackoverflow.com/questions/13812703/c11-emplace-back-on-vectorstruct
`