5

我在shared_ptr.

这是我最终得到的结果:

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;
}

std::find但是,我什至没有设法做到这一点std::find_if。有没有更符合 c++ 的方法来实现这一点?

编辑:这是我得到答案后的代码:

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();
}
4

3 回答 3

6

尝试:

std::find_if(blocks.begin(), blocks.end(), 
  [block](std::shared_ptr<Block> const& i){ return i.get() == block; });
于 2013-02-17T01:45:57.053 回答
2

更简单:

bool contains(Block* block) {
  return std::any_of(blocks.cbegin(), blocks.cend(),
                     [block](std::shared_ptr<Block> const& i) { return i.get() == block; });
}
于 2016-01-10T18:40:41.660 回答
1

根据其他人的回答和评论,以下是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;
}

这是输出:

block1 is in the container
block2 is not in the container
于 2013-02-17T03:04:03.447 回答