Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why queue accepts vector as its underlying container?

Tags:

c++

c++11

stl

c++14

Consider the following piece of code:

std::queue<int, std::vector<int>> Q;
Q.push(1);
Q.push(2);

Live Demo

Beside of the fact that using a container with contiguous memory as the underlying container of a std::queue would significantly deteriorate the queueing operations' performance, the above piece of code is perfectly acceptable and compiles. However, if we call the std::queue::pop member function (e.g., Q.pop();) the program fails to compile, and the compiler rightfully complains that std::vector hasn't got member function pop_front.

Live Demo

Questions:

  1. Why is std::vector acceptable as an underlying container for std::queue since it doesn't satisfy std::queue's criteria?
  2. Isn't some short of meta-programming magic to check whether the underlying container of std::queue fulfils the necessary criteria in the line of queue's definition (e.g., std::queue<int, std::vector<int>> Q;)?
  3. Could the advent of concepts-lite, probably in C++17, solve this problem?
like image 970
101010 Avatar asked Nov 11 '22 05:11

101010


1 Answers

Why is std::vector acceptable as an underlying container for std::queue since it doesn't satisfy std::queue's criteria?

It's not.

Isn't some short of meta-programming magic to check whether the underlying container of std::queue fulfils the necessary criteria in the line of queue's definition (e.g., std::queue<int, std::vector<int>> Q;)?

This sentence doesn't make sense, but if you're asking whether it's possible to diagnose this at instantiation, the answer is yes. It would largely be a waste of time, though. For comparison, note how out-of-bounds std::vector::operator[] is also your responsibility and will not result in a diagnostic.

Could the advent of concepts-lite, probably in C++17, solve this problem?

Insomuch as it's a "problem" at all, yes.

like image 180
Lightness Races in Orbit Avatar answered Nov 15 '22 08:11

Lightness Races in Orbit