gpt4 book ai didi

c++ - 如何有效地从 forward_list 中删除一个元素?

转载 作者:可可西里 更新时间:2023-11-01 18:16:04 26 4
gpt4 key购买 nike

好吧,我认为这个问题已经很概括了。我有一个独特项目的 forward_list,并想从中删除单个项目:

std::forward_list<T> mylist;
// fill with stuff

mylist.remove_if([](T const& value)
{
return value == condition;
});

我的意思是,这种方法工作正常,但效率低下,因为一旦找到并删除项目,它就会继续搜索。有更好的方法还是我需要手动完成?

最佳答案

如果只想删除第一个匹配项,可以使用 std::adjacent_find 后跟成员 erase_after

#include <algorithm>
#include <cassert>
#include <forward_list>
#include <iostream>
#include <ios>
#include <iterator>

// returns an iterator before first element equal to value, or last if no such element is present
// pre-condition: before_first is incrementable and not equal to last
template<class FwdIt, class T>
FwdIt find_before(FwdIt before_first, FwdIt last, T const& value)
{
assert(before_first != last);
auto first = std::next(before_first);
if (first == last) return last;
if (*first == value) return before_first;
return std::adjacent_find(first, last, [&](auto const&, auto const& R) {
return R == value;
});
}

int main()
{
auto e = std::forward_list<int>{};
std::cout << std::boolalpha << (++e.before_begin() == end(e)) << "\n";
std::cout << (find_before(e.before_begin(), end(e), 0) == end(e)) << "\n";

auto s = std::forward_list<int>{ 0 };
std::cout << (find_before(s.before_begin(), end(s), 0) == s.before_begin()) << "\n";

auto d = std::forward_list<int>{ 0, 1 };
std::cout << (find_before(d.before_begin(), end(d), 0) == d.before_begin()) << "\n";
std::cout << (find_before(d.before_begin(), end(d), 1) == begin(d)) << "\n";
std::cout << (find_before(d.before_begin(), end(d), 2) == end(d)) << "\n";

// erase after
auto m = std::forward_list<int>{ 1, 2, 3, 4, 1, 3, 5 };
auto it = find_before(m.before_begin(), end(m), 3);
if (it != end(m))
m.erase_after(it);
std::copy(begin(m), end(m), std::ostream_iterator<int>(std::cout, ","));
}

Live Example

一旦找到匹配项,这将立即停止。请注意,adjacent_find 采用二元谓词,通过仅比较第二个参数,我们在要删除的元素之前得到一个迭代器,这样 erase_after 就可以实际删除它.复杂度为 O(N),因此没有比这更高效的了。

关于c++ - 如何有效地从 forward_list 中删除一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19375403/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com