标记不属于向量的索引C++优雅的方法
C++ elegant way to mark index which doesn't belong to a 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 常量标记不在向量中的索引是个好主意吗?它会导致有关比较有符号和无符号值的警告,但它仍然按照我想要的方式工作。
我不想另外检查我的 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标准在细节方面是模棱两可和分散的。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 枚举环境变量的惯用C++14/C++17方法
- 初始化具有非默认构造函数的std::数组项的更好方法