Access c++ queue elements like an array

This is a task ideal for std::deque. Its optimized for adding/removing onto the end but also provides random access to elements in the middle. To quote the linked article:

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

So because it can efficiently add/remove from both ends, deque can be used efficiently as a queue with its push_back and pop_front methods:

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 also support the random access through the subscript operator:

std::cout << aDeque[0];

Can queue elements be accessed like an array?

Sure! As long as the underlying container (which defaults to deque) does, though you might want to call the code bad names...

template<class T, class C=std::deque<T> >
struct pubqueue : std::queue<T, C> {
  using std::queue<T, C>::c;

  static C& get_c(std::queue<T, C> &s) {
    return s.*&pubqueue::c;
  }
  static C const& get_c(std::queue<T, C> const &s) {
    return s.*&pubqueue::c;
  }
};

template<class T, class C>
C& get_c(std::queue<T, C> &a) {
  return pubqueue<T, C>::get_c(a);
}
template<class T, class C>
C& get_c(std::queue<T, C> const &a) {
  return pubqueue<T, C>::get_c(a);
}

int main() {
  std::queue<int> q;
  q.push(42);
  std::cout << get_c(q)[0] << '\n';

  pubqueue<int> p;
  p.push(3);
  std::cout << p.c[0] << '\n';

  return 0;
}

Notice the trick that allows you to change your std::queue variables to pubqueue variables and just access the container member directly. This lets you keep the push/pop (instead of push_back/pop_front, etc.) interface of std::queue.

Tags:

C++

Queue

Stl