Search code examples
c++vectorunsigned

C++ elegant way to mark index which doesn't belong to a vector


I was wondering about a proper and elegant way to mark index which doesn't belong to a vector/an array. Let me show you a brief example showing what I mean (using some pseudocode phrases):

std::vector<**type**> vector;

int getIndex()
{
   if (**user has selected something**)
   {
      return **index of the thing in our vector**;
   } else
      return -1;
}

int main()
{
   int selectedItem = getIndex();

   if (selectedItem<vector.size()) //checking if selected index is valid, -1 is not
   {
     **do something using selected object**
   }
}

Of course I mean to use it in much more sophisticated way, but I hope the problem is shown in the example. Is it a good idea to mark an index which is not in a vector using -1 constans? It leads to a warning about comparing signed and unsigned values, but still it works as I want it to.

I don't want to check additionaly if my selectedItem variable is -1, that gives one additional, unnecessary condition. So is this a good solution or should I consider something else?


Solution

  • The most elegant way to indicate that something you're looking for wasn't found in a vector is to use the C++ Standard Library facilities the way they were intended -- with iterators:

    std::vector<type>::iterator it = std::find (vec.begin(), vec.end(), something_to_find);
    if (it != vec.end())
    {
      // we found it
    }
    else
    {
      // we didn't find it -- it's not there
    }