c++ - 返回包含输入容器特定元素的容器的函数

标签 c++ stl copy

我有一个 vectorlist,我只想将代码应用于特定元素。例如

class Container : public std::vector<Element*>

或者

class Container : public std::list<Element*>

和:

Container newContainer = inputContainer.Get(IsSomething);
if (!newContainer.empty()) {
    for (Element* const el: newContainer ) {
        [some stuff]
    }
} else {
    for (Element* const el : inputContainer) {
        [some stuff]
    }
}

我写了一个成员函数Get()如下。

template<typename Fn>
auto Container::Get(const Fn& fn) const {
    Container output;
    std::copy_if(cbegin(), cend(), std::inserter(output, output.end()), fn);
    return output;
}

IsSomething 将是一个 lambda,例如

auto IsSomething= [](Element const* const el)->bool { return el->someBool; };

从性能的角度来看:这是一个好的方法吗?还是复制并删除会更好?

template<typename Fn>
auto Container::Get(const Fn& fn) const {
    Container output(*this);
    output.erase(std::remove_if(output.begin(), output.end(), fn), end(output));
    return output;
}

或者有更好的方法吗?

编辑:不同的例子

由于我之前的示例可以用更好的方式编写,让我们展示一个不同的示例:

while (!(container2 = container1.Get(IsSomething)).empty()&&TimesFooCalled<SomeValue)
{
    Container container3(container2.Get(IsSomething));
    if (!container3.empty()) {
        Foo(*container3.BestElement());
    } else {
        Foo(*container2.BestElement());
    }
}

最佳答案

不回答您的直接问题,但请注意,您可以在不复制任何内容的情况下实现原始算法。像这样:

bool found = false;
for (Element* const el: inputContainer) {
  if (IsSomething(el)) {
    found = true;
    [some stuff]
  }
}
if (!found) {
  for (Element* const el : inputContainer) {
    [some stuff]
  }
}

关于c++ - 返回包含输入容器特定元素的容器的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51728529/

相关文章:

c++ - 来自 MPI 的奇怪段错误

c++ - 多维数组,等效数组对象,带键字符串的 vector

c++ - 这是在 C++ 中将一个类对象包含在另一个类中的最佳方式

c++ - 智能指针 - 程序终止时的段错误

java - 从 jar 中复制 Eclipse p2 接触点

c++ - 用于桌面应用程序的轻量级 html 控件 (C++/Windows)

c++如何创建一个在终端和文件上打印的函数

c++ - 基于范围的和双端队列与 vector

python - 为什么不是数组[:] copying the array?

python - 如何修改 pandas 数据框的一个 "cell"中的值?