可以像数组一样访问队列元素吗?如果没有,那么什么类似于队列的容器呢?
解决方法
这是一个非常适合
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
std::cout << aDeque[0];