0

I have an vector word_list, and i want to find an word in word_list. I use function

bool Mylayer::existWord(vector<string> word_list, string word)
{ 
    if (std::lower_bound(word_list.begin(), word_list.end(), word) != word_list.end())
    {
        return true;
    }
    return false;
}

but it find not exactly. Can some one tell me why ?

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
Mr Vy
  • 15
  • 5

2 Answers2

7
  • Your method should look like:

    bool Mylayer::existWord(
        const std::vector<std::string>& words,
        const std::string& word) const
    { 
        return std::find(words.begin(), words.end(), word) != words.end();
    }
    
  • If your vector is sorted, you may use std::binary_search:

    bool Mylayer::existWord(
        const std::vector<std::string>& words,
        const std::string& word) const
    { 
        assert(std::is_sorted(words.begin(), words.end())); // debug check
        return std::binary_search(words.begin(), words.end(), word);
    }
    
  • If your collection is sorted without duplicate, you may use a std::set<std::string> and your method becomes:

    bool Mylayer::existWord(
        const std::set<std::string>& words,
        const std::string& word) const
    { 
        return words.count(word) != 0;
    }
    
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • i have a question: does Find function distinguish uppercase and lowercase ? – Mr Vy Jul 29 '14 at 09:15
  • @MrVy: as `std::string`, so yes. An easy way to manage that is to *lower case* all strings (see [stl-string-to-lower-case](http://stackoverflow.com/questions/313970/stl-string-to-lower-case) for how to do that). An other way is to use `find_if` with a predicate. – Jarod42 Jul 29 '14 at 09:26
-1

you may try using find

ideone link: http://ideone.com/bgFZwU

bool existWord(vector<string> word_list, string word) {
    vector<string>:: iterator it;

    it= find(word_list.begin(), word_list.end(), word);
    if(it== word_list.end()) {
        return 0;
    } else {
        return 1;
    }
}
Niraj
  • 477
  • 6
  • 16