std::find,returns 找到所有值的替代方法,而不仅仅是第一个存在重复项的向量

std::find, alternative method that returns all found values instead of just the first for vector where duplicate exists

我一直在用 std::find 在具有重复值的向量中进行一些测试

我注意到 std::find 总是 return 重复项中的第一个值,例如当我在向量 vecDup:

中查找值 2 时
std::vector<int> vecDup = { 0, 5, 1, 2, 2, 4 };

auto valIterator = (std::find(vecDup.begin(), vecDup.end(), 2));
if (valIterator != vecDup.end()) {
    int value = (*valIterator);
    int valueIndex = std::distance(vecDup.begin(), valIterator);
    std::cout << "Duplicate value: " << value << " at index " << valueIndex << std::endl;
}

Duplicate value: 2 at index 3

文档指出 std::find: Returns 指向范围 [first,last) 中比较等于 val 的第一个元素的迭代器。如果没有找到这样的元素,则函数 return 是最后一个。

所以我想 std::find 不能用于查找多个值。所以我的问题是,我可以使用什么(如果有的话)std 方法以一种或另一种形式获取这些多个值?我唯一需要的输出是对存在这些重复项的索引的某种引用。

编辑

我知道这不是一个特别困难的问题,使用 for 循环可以很容易地实现。我只是认为这可能是一个常见问题,可能已经有某种内置方法可以实现这一点。

如果我没说错的话,您希望有不同的迭代器指向向量中特定元素的每个副本。然后,永远追求好的 ol' for 循环:

std::vector<std::vector<int>::iterator> vec_of_dup_iters;
auto it = vecDup.begin();
for(it = std::find(it, vecDup.end(), elem); it != vecDup.end(); it = std::find(it, vecDup.end(), elem)) {
    vec_of_dup_iters.push_back(it++);
}

但是,我建议不要存储这么多向量,而是存储索引并在需要时生成向量:

std::vector<unsigned> vec_of_indices;
for(size_t index = 0; index < vecDup.size(); index++) {
    if(vecDup.at(index) == elem) {
        vec_of_indices.push_back(index);
    }
}

然后将索引添加到vecDup.begin()生成迭代器

Can this be achieved using std::find

是的。您可以使用以下算法:

Let It be an iterator to the beginning list
while It is not end
    Use std::find to search starting from It, and store result in It
    if It is not end
        add It to set of results (or the index)
        increment It

相反,老式循环可能更简单:

for i in [0, vecDup.size()[
    if vecDup[i] matches the predicate
        add i to set of results