Return empty row vector if key not found

I know this is a very bad idea, so other suggestions on how to do this effectively will be well received.

Here is the thing. At me map<string,vector<string> >, I want to search for a key and return its corresponding value (a vector of lines in this case). The reason I insist on returning (not just repeating) is to find the values ​​returned in some other vector.

In this example, it will be clear:

Input:

key1 ---> {2,3,4}
key2 ---> {1}
key3 ---> {2,12,11,9}

To enter key 1, a vector with values ​​2,3,4 must be returned. Now these 2,3,4 values ​​need to be searched in another row vector. What is the most efficient way to do this?

I tried something like this:

vector<string> returnEdges(string key)
{
    for (map<string, vector<string> >::iterator it=outgoing.begin();
    it!=outgoing.end();++it)
    {
        if (key.compare((*it).first)==0)
        {
            return (*it).second;
        }
    }


    //return string<;//what should I return here????


}

1) How to return an empty vector if the key is not found?

2) What is the best way to implement this?

I hope the question is clear.

EDIT: , , ? SO ?

+5
4

1) - . , " " .end(). , : .end(), , , ( ).

2) , . = , . , - drum roll - .

3) . . ( map find - /. , list, vector deque, std::find, <algorithm>.

4) ( , std::string), ( , ) const. ; , , . , , ++, , , , ? , .

, . - ( , ) NULL, . " " , , .

5) "" , - , . OTOH, , , , , .

6) typedefs.

, :

typedef map<string, vector<string> >::iterator graph_iterator;
graph_iterator edges_named(const string& node_name) {
    return outgoing.find(node_name);
}

, :

typedef map<string, vector<string> >::iterator graph_iterator;
vector<string> edges_named(const string& node_name) {
    graph_iterator it = outgoing.find(node_name);
    return it == outgoing.end() ? vector<string>() : it->second;
}

, :

typedef map<string, vector<string> >::iterator graph_iterator;
vector<string>* edges_named(const string& node_name) {
    graph_iterator it = outgoing.find(node_name);
    return it == outgoing.end() ? NULL : &(it->second);
}

.

+4

:

std::vector<std::string> find_by_key_maybe(const std::string & key)
{
  std::map<std::string, std::vector<std::string>>::const_iterator it = themap.find(key);
  return it == themap.end() ? std::vector<std::string>() : it->second;
}

, themap const, :

std::vector<std::string> find_by_key_and_insert_if_missing(const std::string & key)
{
  return themap[key];
}

, , .

+2

, , const . , .

, find.

const vector<string> & returnEdges(string key)
{
    map<string, vector<string> >::iterator it = outgoing.find(key);
    if (it == outgoing.end())
    {
        static vector<string> empty_vector;
        return empty_vector;
    }
    return it->second;
}
+1

, [] , ( ). , , ,

vector<string> returnEdges(string key) 
{
    return outgoing[key];
}
0

All Articles