开发者

examining if std::find fails while searching in a vector of vectors

The problem I am facing is that std::find returns <someVector>.end() if it fails, but what if you don't know that <someVector> ??

St开发者_如何学编程ructure to search : hashtable (vector H of vectors of class X) the index(i) of outer vector H is found using hash function std::find is used to search through H[i] function signature : <return val> lookup (hashtable H, ) [<return val> is a handle to the element found by lookup, so that we can change it's value as needed]

vector<X>::iterator lookup (vector <vector <X>> &H, X some_value)
{
     int index = hashFn(some_value);
    return std::find(H[index].begin(), H[index].end(), some_value);
}

how do i check in this case if lookup fails ?? (if I change vector to arrays/pointers, I can simply return NULL and the deal is done, but how do i do this when returning iterators ??)


std::find(a,b, V) doesn't return .end(); it returns its second argument. Since you, the caller, passed that argument, you always know it.

Now, in your more complex example, it appears that the problem is what the caller of std::find() should return to its caller. That's something we can't really say; we don't even know the signature. You could return an empty vector, default constructed (see Monish's answer). You could throw an exception (if that makes sense, conceptually). You could return a const reference to a static, empty vector.


W/o being able to access vector itself the only thing you can do with iterator is to retrieve element that is pointed by this iterator. So why you don't want to return const X* or X* instead of vector::iterator? In case of fail you may just return 0 (or nullptr if you are using C++11). Thats about interface. What about the way you can detect std::find fail in your search algorithm - I agree with MSalters - there is std::find call somewhere in your code with arguments available - so you can just compare result with second argument in that place and return zero-pointer on equality.

X * lookup ( vector <vector <X>> &H, X some_value )
{
  int index = hashFn(some_value);
  vector<X> &v = H[index];
  const vector<X>::iterator result = std::find( v.begin(), v.end(), some_value );
  if ( result != v.end() ) {
    return &(*result);
  } else {
    return 0;
  }
}

Usage:

X * value = hash_table.lookup(...);
if ( X != 0 ) {
  // use result
} else {
  // value not found
}

And again - you would not be able to use iterator in any other way w/o access to vector, so it's pointless to use vector::iterator as lookup's return type;


If the return type is vector<X>, then you can return empty vector in case lookup fails.

return vector<X>();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜