Find multiple occurrences of a word in a vector of string

Hello everyone,

i'm trying to find (as the title says) multiple occurrences od a word in a vector of string.

Now i can find a single word in the vector as follow:



1
2
3
4
5
6
7
8
9
int findWordLocation(string wordType) {
vector<string>::iterator it;
it=find(myWord.begin(), myWord.end(), wordType)
if (it !=myWord.ed()) {
     return (it-myWord.begin());
}else{
   return -1;
}
}


and this works very well.

What i want to do is to modify the routine to push the name of the founded wordType in a vector and then return it.

How can i do this?

Thank you in advance
find(myWord.begin(), myWord.end(), wordType)
see that `find()' ask for two iterators, `begin' and `end'
If you do find(it+1, myWord.end(), wordType) you'll search for the next ocurrence. Keep doing that until the search fails to have all ocurrences.
Thank you for the reply.

Should i use the find(it+1, myWord.end(), wordType) after the first use of find or what?

Could you provide a complete example?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <vector>

std::vector<std::size_t> locate_all( const std::vector<std::string>& seq, const std::string& what )
{
    std::vector<std::size_t> result ;
    for( std::size_t i = 0 ; i < seq.size() ; ++i ) if( seq[i] == what ) result.push_back(i) ;
    return result ;
}

int main()
{
    const std::string cat = "cat" ;
    const std::vector<std::string> my_words { "cat", "dog", cat, "bird", cat, "cat", "elephant", cat };

    std::cout << "word '" << cat << "' was found at positions: " ;
    for( auto pos : locate_all( my_words, cat ) ) std::cout << pos << ' ' ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/90bc19ef2fd989f2
Topic archived. No new replies allowed.