是否可以同时从C std :: vector或std :: deque中删除并获取对象
发布时间:2020-12-16 06:47:09 所属栏目:百科 来源:网络整理
导读:在 Java中,Deque类的末尾有 removal methods,实际返回返回的元素. 在C中,似乎实现相同行为的唯一方法是首先显式复制元素然后弹出它. std::dequeint myDeque;myDeque.push_back(5);int element = myDeque.back();myDeque.pop_back(); 是否有同时进行这两种机
在
Java中,Deque类的末尾有
removal methods,实际返回返回的元素.
在C中,似乎实现相同行为的唯一方法是首先显式复制元素然后弹出它. std::deque<int> myDeque; myDeque.push_back(5); int element = myDeque.back(); myDeque.pop_back(); 是否有同时进行这两种机制的机制? 解决方法
您可以编写自己的包装函数模板:
// Precondition: !container.empty() // Exception safety: If there is an exception during the construction of val,// the container is not changed. // If there is an exception during the return of the value,// the value is lost. template <typename C> auto back_popper(C & container) -> decltype(container.back()) { auto val(std::move(container.back())); container.pop_back(); return val; } 用法: auto element = back_popper(myDeque); 你无法解决首先激发back()和pop_back()分离的基本问题,即元素的复制或移动构造函数可能抛出异常,并且当发生这种情况时你可能会丢失弹出元素.您可以通过返回非投掷对象来逐个缓解它,例如: unique_ptr,可以消除动态分配丢失元素的风险,但显然这是个人选择,你必须做出标准不适合你. 例如: // Guarantees that you either get the last element or that the container // is not changed. // template <typename C> auto expensive_but_lossless_popper(C & container) -> typename std::unique_ptr<decltype(container.back())> { using T = decltype(container.back()); std::unique_ptr<T> p(new T(std::move(container.back()))); container.pop_back(); return p; // noexcept-guaranteed } 编辑:我添加了std :: move围绕back()调用,正如@Simple建议的那样.这是合法的,因为不再需要move-from元素,并且许多真实世界的类都带有noexcept移动构造函数,因此这涵盖了大量的情况,而“无损”的解决方法只为少数几个提供了优势.没有noexcept动作的“怪异”类型. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |