将pop_front实现为std::vector的快速方法
Fast way to implement pop_front to a std::vector
我正在使用一些类和一些使用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
相关文章:
- 使 std::vector 分配对齐内存的现代方法
- 我无法使用C++指针指向类方法返回的 std::vector
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 在 std::vector<无符号字符中存储任意数据的方法>
- 连接和压缩标准::vector<std::字符串的最佳方法>
- C++中的多维数据集:从 std::vector 的 2D 数据到 std::vector 的 2D 网格的最干净方法?
- 向后迭代 std::array 或 std::vector 的正确方法是什么?
- 使用 std::vector::swap 方法在C++中交换两个不同的向量是否安全?
- 有没有更快的方法可以在 std::vector 中插入元素
- 为什么 vector 的方法调整大小会创建一个额外的对象?
- 将vector<vector<double>>从x86平台中创建的一个进程发送到x64中构建的另一个进程的最快方法是什么
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 释放 std::vector 中指针内存的最有效方法是什么?
- 编译错误 std::vector<std::shared_ptr<T>>迭代器和擦除方法
- C++ std::vector 赋值方法
- 使用虚拟变量对 std::vector 内部循环进行切片的最佳方法
- 如何在不使用 vector::erase() 的情况下编写自定义 Vector 方法来删除元素?
- STL vector.insert 方法期望_InputIterator作为参数
- 动态创建 std::vector 并将其传递给另一个函数的各种方法
- 从 std::vector 创建 OpenCV 垫子的有效方法