将pop_front实现为std::vector的快速方法

Fast way to implement pop_front to a std::vector

本文关键字:vector 方法 std pop front 实现      更新时间:2023-10-16

我正在使用一些类和一些使用std::vector的实用程序方法。

现在,我需要在其中一个类上使用每个帧的pop_front-push_back方法(但它们都是链接的,并且一起工作,所以我不能只更改一个)。

大多数操作都是对所有元素和push_back操作进行迭代,所以我应该做的最好的工作是:派生这些类和实用程序的存储库,对所有内容进行模板化,并使用deque或list。

但这意味着大量的代码重写和大量的测试,这将使我错过最后期限。

因此,我需要建议将一个有效的pop_front写入静态大小向量(大小不会改变)。

我在这里找到了一种方法:

template<typename T>
void pop_front(std::vector<T>& vec)
{
   vec.front() = vec.back();
   vec.pop_back();
   vec.front() = vec.back();  // but should this work?
}

另一个想法应该是:

template<typename T>
void pop_front(std::vector<T>& vec, already_allocated_vector vec1)
{
   vec1.clear();
   copy(vec.begin(), vec.end()-1, vec1.begin());
   copy(vec1.begin(), vec1.end(), vec.begin());
}

这两种解决方案中速度更快的是什么?还有其他解决方案吗?

我希望:

template<typename T>
void pop_front(std::vector<T>& vec)
{
    assert(!vec.empty());
    vec.front() = std::move(vec.back());
    vec.pop_back();
}

是最有效的方法,但它不保持向量中元素的顺序。

如果您需要维护vec中剩余元素的顺序,您可以执行以下操作:

template<typename T>
void pop_front(std::vector<T>& vec)
{
    assert(!vec.empty());
    vec.erase(vec.begin());
}

这将使vec中的元素数量具有线性时间,但这是在不更改数据结构的情况下所能做到的最好的方法。

这两个函数都不会将vector保持在恒定大小,因为根据定义,pop_front操作将从容器中移除元素。

由于pop_front()只擦除第一个元素,因此直接实现如下:

template <typename V>
void pop_front(V & v)
{
    assert(!v.empty());
    v.erase(v.begin());
}

现在不要担心速度。如果您想返回并优化代码,请请求专用的项目时间。

我也有办法。。。不太好但是。。

这看起来像@0xPwn的解决方案,但他第二次没有反转矢量。你可能会理解这个代码,所以我不会解释它。

#include <algorithm>
#include <vector>
template <typename T>
void pop_front(std::vector<T>& vec){
    std::reverse(vec.begin(),vec.end()); // first becomes last, reverses the vector
    vec.pop_back(); // pop last
    std::reverse(vec.begin(),vec.end()); // reverses it again, so the elements are in the same order as before
}

如果你只是试图擦除第一个元素,那么在函数中使用:

if (my_vector.size()){ //check if there any elements in the vector array
    my_vector.erase(my_vector.begin()); //erase the firs element
}

如果你想模拟整个矢量数组的pop-front(你想从头到尾保持每个元素的pop-out),我建议使用:

reverse(my_vector.begin(),my_vector.end());  // reverse the order of the vector array
my_vector.pop_back();   // now just simple pop_back will give you the results
相关文章: