访问c队列元素,如数组

前端之家收集整理的这篇文章主要介绍了访问c队列元素,如数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
可以像数组一样访问队列元素吗?如果没有,那么什么类似于队列的容器呢?

解决方法

这是一个非常适合 std::deque的任务.它的优化是为了添加/删除到最后,但也可以随意访问中间的元素.引用链接文章

A deque is very much like a
vector: like vector,it is a sequence
that supports random access to
elements,constant time insertion and
removal of elements at the end of the
sequence
,and linear time insertion and removal of elements in the middle.

deque also supports constant time insertion and removal of elements at the beginning of the sequence

所以因为它可以从两端有效地添加/删除,所以deque可以有效地用作其push_back和pop_front方法的队列:

std::deque<int> aDeque;

// enqueue
aDeque.push_back(1);
aDeque.push_back(2);

// dequeue
int top = aDeque.front();
aDeque.pop_front();

Accessing elements like an array means using the subscript operator

deque还支持通过下标运算符的随机访问:

std::cout << aDeque[0];
原文链接:https://www.f2er.com/c/115132.html

猜你在找的C&C++相关文章