Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting index of an element in a std::queue by its value

Tags:

c++

stl

queue

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
like image 554
giladk Avatar asked Jan 22 '19 14:01

giladk


People also ask

Does queue have index?

Unlike ArrayList , there is no get(int index) method in Queue to retrieve the element at specified position.


1 Answers

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.

like image 54
ネロク・ゴ Avatar answered Sep 17 '22 06:09

ネロク・ゴ