0

I am not using boost libraries. How can i do this using STL?

class Files
{

private:
   bool isSame(FileID f1, FileId f2)
   { 
      if(f1.getId()==f2.getId())
        return true;
      return false;
   }

public:
   vector<FileId> mod_files;

    void update()
    {
      FildId f = getFileId();
      vector<FildId>::const_iterator found = find_if(mod_files.begin(), mod_files.end(),          ???);
    }

};

I would like to pass isSame as the third argument to find_if function, and bind "f" to the isSame's second argument.

1
  • I think you want your private and public switched. that way you can call "isSame" from outside the class. Commented Jun 19, 2012 at 1:57

1 Answer 1

4

In C++11 that's simply:

std::bind(&Files::isSame, this, f);

In good old C++03 there is no mem_fun that takes 2 arguments, so you would have to do the binding on your own:

class is_same_pred
{
public:
    // unary function typedefs

    explicit is_same_pred(Files& files, FileId f1) : _files(files), _f1(f1) {}

    bool operator()(FileId f2) const { return _files.isSame(_f1, f2); }

private:
    Files& _files;
    FileId _f1;
};

Where isSame is accessible to is_same_pred, and later use it like this:

is_same_pred(this, f);

All that said and done, you would be better off defining isSame as a static or free-function:

bool isSame(FileId f1, FileId f2){ ... }

std::bind1st(std::ptr_fun(&isSame), f);
Sign up to request clarification or add additional context in comments.

2 Comments

Just to throw in my two cents, I think once we get to writing our own predicates or trying to do things with bind1st, mem_fun, etc.: it's time to consider letting go of find_if and just writing a simple old vanilla search loop which everyone is used to doing. Unless we have the tools (C++11/boost, e.g.) and experience necessary so that generic algorithms flow freely and naturally from our fingertips, I think they should be avoided. If it's giving us headaches to write it in the first place, most people probably wouldn't want to debug it.
+1 for pointing out that isSame has no benefits being a non-static method, and I wish I could give another +2 for pointing out that what he wants to do exactly as he's doing it is impossible in C++03 using just mem_fun (nullary to unary, not binary to ternary) and STL binders

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.