我想知道一种适当而优雅的方法来标记不属于 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/