gpt4 book ai didi

c++ - 是否可以同时从 C++ std::vector 或 std::deque 中删除和获取对象的拷贝?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:25:39 25 4
gpt4 key购买 nike

在 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
}

编辑:我按照@Simple 的建议在back() 调用周围添加了std::move。这是合法的,因为不再需要 moved-from 元素,并且许多现实世界的类都带有 noexcept move 构造函数,因此这涵盖了大量情况,而“无损”变通方法只为少数情况提供了优势没有 noexcept Action 的“怪异”类型。

关于c++ - 是否可以同时从 C++ std::vector 或 std::deque 中删除和获取对象的拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19723614/

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