通过值获取 std::queue 中元素的索引 [英] Getting index of an element in a std::queue by its value

查看:37
本文介绍了通过值获取 std::queue 中元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以通过 C++ 中的值获取 std::queue 中元素的位置?

Is there a simple way to get the position of an element in a std::queue by its value in C++?

例如:

std::queue<int> numbers;

numbers.push(7);
numners.push(4);
numbers.push(11);

int position = numbers.getPosition(4); //should be 1

推荐答案

如果您想获取元素的索引,您可能应该考虑使用 std::deque 容器而不是 std::queue 容器 adapter,正如其他答案中已经建议的那样.

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.

如果您仍想坚持使用 std::queue 容器适配器出于某些其他原因,您应该知道它确实通过 protected 数据成员 c 提供对底层容器的访问.

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.

您可以从 std::queue 派生以访问底层容器并使用 std::find() 函数模板,用于在该容器中查找具有此类值的元素.然后,只需使用 std::distance()<返回该元素的位置/code>.

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);
   }
// ...
};

如果未找到该元素,则索引将对应于 size() 成员函数返回的索引.

If the element is not found, the index will correspond to the one returned by the size() member function.

如果有重复,这个基于std::find()的解决方案将返回第一个的位置,即找到的第一个具有请求值的元素val.

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.

这篇关于通过值获取 std::queue 中元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆