在set中使用find_if

时间:2011-05-18 05:07:42

标签: c++

在我的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;
}

当我编译程序时,它出错了:

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'

anyboy可以告诉我哪里错了吗?谢谢

1 个答案:

答案 0 :(得分:11)

std::find_if返回找到的元素的迭代器(如果没有元素与谓词匹配,则返回一个结尾):

std::set<std::string>::iterator it = 
    std::find_if(myset.begin(), myset.end(), findme());
if (it != myset.end())
{
    // etc.