Is there a simple way to get the position of an element in a std::queue
by its value in C++?
For example:
std::queue<int> numbers;
numbers.push(7);
numners.push(4);
numbers.push(11);
int position = numbers.getPosition(4); //should be 1
Unlike ArrayList , there is no get(int index) method in Queue to retrieve the element at specified position.
If you want to get the index of an element you should probably consider using an std::deque
container instead of a std::queue
container adapter, as already suggested in this other answer.
If you still want to stick to to the std::queue
container adapter for some other reason, you should know that it does provide access to the underlying container through the protected data member c
.
You could derive from std::queue
in order to access the underlying container and use the std::find()
function template for finding an element in that container with such a value. Then, simply return the position of that element by using std::distance()
.
#include <algorithm>
#include <queue>
template<typename T>
class Queue: std::queue<T> {
public:
auto getPosition(const T& val) const {
auto it = std::find(this->c.begin(), this->c.end(), val);
return std::distance(this->c.begin(), it);
}
// ...
};
If the element is not found, the index will correspond to the one returned by the size()
member function.
If there are duplicates, this solution based on std::find()
will return the position of the first one, i.e., the first element found with the requested value val
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With