如何在 std::vector 中查找项目的位置

How to find the positions of an item in a std::vector

本文关键字:查找 项目 位置 vector std      更新时间:2023-10-16

我的问题与如何在 std::vector 中查找项目非常相似?但是,我想更进一步,假设我正在搜索的项目在向量中出现多次,并且我也想获得它在向量中的位置。例如,我拥有的向量是[ 1 3 4 3 7],而我要搜索的项目是3。然后项目的位置是13。使用 std::find 函数,我只能获得它在向量中的第一个位置。有什么想法吗?

只需将其粘贴在 while 循环中,

    auto i = std::find(v.begin(), v.end(), n);
    std::vector<std::size_t> result;
    while(i != v.end())
    {
      result.push_back(std::distance(v.begin(), i));
      i = std::find(i + 1, v.end(), n);
    }

连续使用std::find次,然后将所有结果放在一起。用作您找到的范围first,前一个std::find返回给您的位置加一。

您可以多次使用 std::find

std::vector<int> vec;
// fill the vector with numbers
std::vector<int>::iterator it = vec.begin();
while (it != vec.end())
{
    it = std::find(it, vec.end(), 3);
    // do something with *it
    if (it != vec.end())
        it++;
}

或者你可以简单地使用std::for_each

std::vector<int> vec;
// fill the vector with numbers
std::for_each(vec.begin(), vec.end(), [&](int i)
{
    if (i == 3)
    {
        // do something
    }
});

如果您正在寻找项目的索引/迭代器,您可以简单地使用自定义循环:

std::vector<int> vec;
// fill the vector with numbers
std::vector<int> results;
for (std::size_t i = 0; i < vec.size(); ++i)
{
    if (vec[i] == 3)
    {
        results.push_back(i);
    }
}

然后,results将保存与您的条件匹配的元素的所有索引(在本例中为 ==3 )。