Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using find_if in set

Tags:

c++

In my main.cpp:

using namespace std;
#include <cstdlib>
#include <iostream>
#include <set>
#include <string>
#include <cstring>
#include <sstream>
#include <algorithm>

class findme
{
  public:
    bool operator()(const std::string& s) {
        return s == "tom";
    }
};

int main(int argc, char *argv[])
{
    set<string> myset;
    myset.insert("tom");
    myset.insert("jerry");
    cout << myset.size();
    set<string>::iterator it;
    if (find_if(myset.begin(), myset.end(), findme())) {
        cout << "found tom \n";   
    }
    return EXIT_SUCCESS;
}

when I compiled the program, it got an error:

Could not convert std::find_if [with _InputIterator = std::_Rb_tree_const_iterator<std::string>, _Predicate = findme]((&myset)->std::set<_Key, _Compare, _Alloc>::begin [with _Key = std::string, _Compare = std::less<std::string>, _Alloc = std::allocator<std::string>](), (&myset)->std::set<_Key, _Compare, _Alloc>::end [with _Key = std::string, _Compare = std::less<std::string>, _Alloc = std::allocator<std::string>](), (findme(), findme()))' to 'bool'

Can anyboy tell me where were I wrong? thank you

like image 783
Xitrum Avatar asked May 18 '11 05:05

Xitrum


1 Answers

std::find_if returns an iterator to the found element (or one-past-the-end if no element matched the predicate):

std::set<std::string>::iterator it = 
    std::find_if(myset.begin(), myset.end(), findme());
if (it != myset.end())
{
    // etc.
like image 177
James McNellis Avatar answered Nov 12 '22 01:11

James McNellis