Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return empty vector by reference

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_;
like image 829
RedFox Avatar asked Oct 27 '25 14:10

RedFox


1 Answers

You could use a static variable:

static const std::vector<ClassA> empty;
return empty;
like image 116
eerorika Avatar answered Oct 30 '25 04:10

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!