I'm returning a vector by reference as shown below and it is getting bit ugly when I want to return an empty vector when there is no item in the map. The following gives warning (returning address of local variable) and to fix it, I have another private member variable vector<ClassA> empty_ and I could return it to avoid this.
I am wondering if there is elegant way to implement this.
const std::vector<ClassA>& GeVector(const std::string& class_id) {
auto iter = class_map_.find(class_id);
if (iter != class_map_.end())
return iter->second;
return {}; // return empty_;
}
private:
std::unordered_map<std::string, std::vector<ClassA>> class_map_;
vector<ClassA> empty_;
You could use a static variable:
static const std::vector<ClassA> empty;
return empty;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With