The requirement is that I need to search a vector to see if it contains the value passed in as the parameter. If the value exists in the vector, I return the vector. Else, I return an empty vector. I am not sure how to return an empty vector in c++. hope you could help me. my mimic.h:
vector<Pair> map;
my Pair.h:
Pair(){ } ~Pair(){} string prefix; vector<string> sufix;
Return vector function :
vector<string> Mimic::getSuffixList(string prefix){ int find=0; for(int i =0; i < map.size(); i++) { if(map[i].prefix == prefix) { find =1; return map[i].sufix; //sufix is a vector from a class called "Pair.h" } } if(find==0) { //return an empty vector. } }
Return vector function : vector<string> Mimic::getSuffixList(string prefix){ int find=0; for(int i =0; i < map. size(); i++) { if(map[i]. prefix == prefix) { find =1; return map[i].
The return by value is the preferred method if we return a vector variable declared in the function. The efficiency of this method comes from its move-semantics. It means that returning a vector does not copy the object, thus avoiding wasting extra speed/space.
C++ Vector Library - clear() Function The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.
You could however make something like an empty pair using Boost. Optional. Then you would either use a boost::optional<std::pair<...>> giving you the option of returning either a pair or an empty state or use std::pair<boost::optional<...>, boost::optional<...>> for a pair where either object could be empty.
Just
return vector<string>();
Or use list initialization (since C++11)
return {};
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