I have code similar to this:
struct Record{
std::string key;
// ...
};
void push_record(Record &out, std::map<std::string, int> &vmap){
const auto &it = vmap.find(out.key);
long pos;
if (it != vmap.end()){
pos = it->second;
}else{
pos = calculate_pos(out);
vmap.insert( Record(std::move(out.key), pos) ); // here move
}
// use pos
}
How can I make the code more efficient?
At the moment, the code is not very efficient, because it lookup into map twice. First when it checks for the value and second when it inserts.
I also want to use std::move(out.key)
, this is why I did not use something like vmap[out.key]
.
I see you can pass suggestions to insert
, but I was unable to find good example.