3

My question is very similar to How to find an item in a std::vector? However, I want to go further, suppose the item I am searching for appears several times in the vector, and I want to obtain its positions in the vector as well. For example, the vector I have is [ 1 3 4 3 7], and the item I want to search is 3. Then the positions of the item is 1 and 3. Using the std::find function, I can only obtain its first position in the vector. Any ideas?

Community
  • 1
  • 1
feelfree
  • 11,175
  • 20
  • 96
  • 167

3 Answers3

7

Just stick it in a while loop,

    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);
    }
SirGuy
  • 10,660
  • 2
  • 36
  • 66
4

Use std::find successive times, and then put all the results together. Use as first of the range in which you find, the position that the previous std::find returned to you plus one.

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
4

You can use std::find multiple times:

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++;
}

Or you can simply use 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
    }
});

If you are looking for the indexes/iterators for the items, you can simply use a custom loop:

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 will then hold all of the indexes for elements matching your criteria (in this case, ==3).

Zac Howland
  • 15,777
  • 1
  • 26
  • 42