Finding an item in a shared_ptr container?

I had a little problem finding an element in a vector shared_ptr.

Here is what I ended up with:

std::vector<std::shared_ptr<Block>> blocks;

bool contains(Block* block) {
  for (auto i = blocks.begin(); i != blocks.end(); ++i) {
    if ((*i).get() == block) {
      return true;
    }
  }
  return false;
}

However, I was not able to do this with std::findor even std::find_if. Is there another C ++ compatible way to achieve this?

EDIT : this is the code I have after the answer:

bool contains(Block* block) {
  auto found = std::find_if(blocks.begin(), blocks.end(), [block](std::shared_ptr<Block> const& i){
    return i.get() == block;
  });
  return found != blocks.end();
}
+5
source share
3 answers

Try:

std::find_if(blocks.begin(), blocks.end(), 
  [block](std::shared_ptr<Block> const& i){ return i.get() == block; });
+6
source

Based on answers and comments from others, here is a fully working selection from ideone :

#include <vector>
#include <memory>
#include <algorithm>
#include <iostream>

using namespace std;

struct Block
{
    bool in_container(const vector<shared_ptr<Block>>& blocks)
    {
        auto end = blocks.end();
        return end != find_if(blocks.begin(), end,
                              [this](shared_ptr<Block> const& i)
                                  { return i.get() == this; });
    }
};

int main()
{
    auto block1 = make_shared<Block>();
    auto block2 = make_shared<Block>();

    vector<shared_ptr<Block>> blocks;
    blocks.push_back(block1);

    block1->in_container(blocks) ?
        cout << "block1 is in the container\n" :
        cout << "block1 is not in the container\n";

    block2->in_container(blocks) ?
        cout << "block2 is in the container\n" :
        cout << "block2 is not in the container\n";

    return 0;
}

Here is the result:

block1 is in the container
block2 is not in the container
+1
source

:

bool contains(Block* block) {
  return std::any_of(blocks.cbegin(), blocks.cend(),
                     [block](std::shared_ptr<Block> const& i) { return i.get() == block; });
}
+1

All Articles