C++ 优雅的方式来标记不属于 vector 的索引

标签 c++ vector unsigned

我想知道一种适当而优雅的方法来标记不属于 vector/数组的索引。让我向您展示一个简短的例子来说明我的意思(使用一些伪代码短语):

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 constans 标记不在 vector 中的索引是个好主意吗?它会导致有关比较有符号和无符号值的警告,但它仍然按我希望的方式工作。

我不想额外检查我的 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
}

关于C++ 优雅的方式来标记不属于 vector 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26997740/

相关文章:

c++ - 会调用析构函数吗?

c - 为什么 uint_least16_t 在 x86_64 中的乘法比 uint_fast16_t 快?

C++ 编译错误(REPAST 库)

c++ - 为什么最低()和最大()之间生成的所有随机数都等于无穷大?

c++ - 初始化 STL `map` 大小

c - 使用 NULL 数组将内存分配给二维数组 (c)

c++ - Oculus Rift/Vulkan : Write to swapchain with a compute shader

c++ - 将派生类指针的 vector 传递给线程

c - 为什么从返回 int32_t 的函数返回 0x80000000 不会导致警告?

c++ - 为什么 int 加上 uint 返回 uint?