gpt4 book ai didi

c++ - 像数组一样访问 c++ 队列元素

转载 作者:IT老高 更新时间:2023-10-28 22:32:11 29 4
gpt4 key购买 nike

可以像数组一样访问队列元素吗?如果不是,那有什么类似于队列的容器可以呢?

最佳答案

这是 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];

关于c++ - 像数组一样访问 c++ 队列元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5877504/

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