在shared_ptr容器中查找元素?

时间:2013-02-17 01:41:02

标签: c++ pointers containers

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

3 个答案:

答案 0 :(得分:6)

尝试:

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

答案 1 :(得分:2)

更简单:

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

答案 2 :(得分: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