我有一个 vector
或 list
,我只想将代码应用于特定元素。例如
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/