标记不属于向量的索引C++优雅的方法

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

本文关键字:方法 C++ 索引 不属于 向量      更新时间:2023-10-16

我想知道一种正确而优雅的方式来标记不属于向量/数组的索引。让我给你看一个简短的例子来说明我的意思(使用一些伪代码短语):

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**
   }
}

当然,我的意思是以更复杂的方式使用它,但我希望问题在示例中得到体现。使用 -1 常量标记不在向量中的索引是个好主意吗?它会导致有关比较有符号和无符号值的警告,但它仍然按照我想要的方式工作。

我不想另外检查我的 selectedItem 变量是否为 -1,这给出了一个额外的、不必要的条件。那么这是一个很好的解决方案还是我应该考虑其他解决方案?

表示您要查找的内容在vector中找不到的最优雅方法是按照预期的方式使用 C++ 标准库设施 - iterator

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
}
最好

使用迭代器,但如果您决定坚持使用索引,最好像string::find()一样getIndex返回size_t

 size_t getIndex()
 {
     //...
     return -1; // the same as std::numeric_limits<size_t>::max()
 }

这样getIndex(element) < vec.size()当且仅当元素存在于向量中时。

如果您坚持使用整数索引而不是迭代器,那么 -1 是用于表示"未找到"的常用哨兵值。但是,与其与vec.size()进行比较,不如与0进行比较,以避免有符号/无符号不匹配。

struct SelectableItem {bool selected;/*more suff here*/};
struct IsSelected(const SelectableItem& sel) {return sel.selected;}
int main(int argc, char** argv)
{
   std::vector<SelectableItem> vec;
   //populate vector
   auto found = vec.find_if(vec.begin(), vec.end(), IsSelected());
   if (found != vec.end())
   {
      SelectedItem& selected_item = *found;
      /*do something*/
   }
}

不要重新发明轮子。

如果您决定使用 vec.end(),那么您可以通过在调试模式下使用 -D_GLIBCXX_DEBUG 进行编译来保护自己免受无效迭代器的影响(例如,在创建迭代器后在向量中插入元素)。

不过我会使用 -1,但在任何地方都使用 size_t 类型。迭代器非常容易出错,ISO标准在细节方面是模棱两可和分散的。