Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return an empty vector c++ [duplicate]

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.     }    } 
like image 274
user3369592 Avatar asked Jun 12 '14 02:06

user3369592


People also ask

How do you return an empty vector 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].

Does returning a vector copy?

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.

How do you empty a vector?

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.

How do I return an empty pair?

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.


1 Answers

Just

return vector<string>(); 

Or use list initialization (since C++11)

return {}; 
like image 137
songyuanyao Avatar answered Sep 29 '22 22:09

songyuanyao