Looking for a prefix in another string in a std::list<string>

I want to send in a string to a function That looks for every word in the list that starts with that prefix and then put that word into another list and return that list.
the code I have isn't doing what I want and I was wondering if I did something wrong.
1
2
3
4
5
6
7
8
9
10
    list<string> Lexicon::startWith(const string& prefix){
    list<string> starts;
    list<string>::iterator it;
    for(it = myLexicon.begin(); it != myLexicon.end(); it++){
        if((*it).find(prefix,0))
            starts.push_front((*it));
    }
    return starts;
}
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 <list>

std::list<std::string> words_starting_with( const std::list<std::string>& lexicon,
                                            const std::string& prefix )
{
    std::list<std::string> result ;

    for( const std::string& str : lexicon )
        if( str.find(prefix) == 0 ) result.push_back(str) ; // note: case sensitive

    return result ;
}

int main()
{
    const std::list<std::string> lexicon { "bird", "dog", "cat", "donkey", "cow", "zebra", "dodo" } ;
    for( const auto& word : words_starting_with( lexicon, "do" ) ) std::cout << word << '\n' ;
}

http://coliru.stacked-crooked.com/a/7096a9a6568bf5b8

Tip: strongly favour std::vector<> over std::list<>
Thanks for the reply but my assignment requires a list. and we never learned that type of for loop, is there a way to do that with the other for loop?
1
2
3
4
5
6
7
8
9
10
11
12
13
std::list<std::string> words_starting_with( const std::list<std::string>& lexicon,
                                            const std::string& prefix )
{
    std::list<std::string> result ;

    for( std::list<std::string>::const_iterator iter = lexicon.begin() ;
         iter != lexicon.end() ; ++iter )
    {
        if( iter->find(prefix) == 0 ) result.push_back(*iter) ; // note: case sensitive
    }

    return result ;
}
Topic archived. No new replies allowed.