遍历以无符号短指针表示的数组



我有一些存在于C中的代码,其中包含uint16_t的数组,它看起来像uint16_t *Fingerprints;。为了迭代它,我可以将它与uint32_t ArrayLength;值配对并直接访问Fingerprints[i]

现在,我正在用c++编写更多代码,并且我有一个std::vector<uint16_t> values,我想通过相同的数据类型进行迭代。是否有可能从中获得uint16_t *并将其与values.size()配对以迭代?

std::vector<uint16_t>有一个.data()成员函数,它会给你一个uint16_t*指针,你可以像在c中使用它一样将它与.size()一起使用。

然而,在c++中,如果没有特定的理由使用指针,我们通常使用迭代器而不是指针。迭代器是指针概念的泛化,也适用于其他类型的容器。这样做的好处是与容器类型无关。如果将std::vector替换为std::list,则不必更改代码中的任何内容。例如:

std::vector<uint16_t> values;
// or e.g. `std::list<uint16_t> values`
for(auto it = values.begin(); it != values.end(); ++it) {
/* You can use `it` here similar to a pointer to the current element */
/* Meaning `it` is similar to `Fingerprints + i` */
}

这样做的好处是,您不会意外地不匹配索引类型。如何确保uint32_t是索引使用的正确类型?如果你是在x64上,并且有一个数组/向量如此之大,以至于无法适应uint32_t。对于数组/向量,它通常应该是std::size_t(或者如果首选有符号的std::ptrdiff_t),对于其他容器,它可能会进一步变化。

此外,还有一个range-for循环语法糖,如果你只想对所有容器进行简单的迭代,你应该更喜欢它:

for(auto&& el : values) {
/* You can use `el` here as a reference to the current element in the iteration */
/* Meaning `el` is basically `Fingerprints[i]` */
}