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?
Asked
Active
Viewed 1,654 times
3
3 Answers
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
-
1+1, but you should use `size_t` instead of `unsigned` for this purpose - your code could fail if these don't match in size (such as a huge vector on a 64-bit system). – Angew is no longer proud of SO Nov 18 '13 at 14:00
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
-
1Thanks for the comments, but if I use std::for_each method, I donot think I can get the item's position. if (i==3) { //do something} How could I get the item's position? – feelfree Nov 18 '13 at 14:16
-
-
-