栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何仅从forward_list中删除单个元素,如何有效地将其删除?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何仅从forward_list中删除单个元素,如何有效地将其删除?

如果你只是想删除的第一场比赛,你可以使用

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 lasttemplate<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, ","));}

现场例子

找到匹配项后,该操作将立即停止。请注意,该

adjacent_find
接受一个二进制谓词,并且通过仅比较第二个参数,我们在要删除的元素之前获得了一个迭代器,因此
erase_after
实际上可以将其删除。复杂性就是
O(N)
这样,您将无法获得比它更有效的效果。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640751.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号