有没有一种简单的方法来获取元素在 a 中的位置std::queue
通过它在 C++ 中的值?
例如:
std::queue<int> numbers;
numbers.push(7);
numners.push(4);
numbers.push(11);
int position = numbers.getPosition(4); //should be 1
如果您想获取元素的索引,您可能应该考虑使用std::deque https://en.cppreference.com/w/cpp/container/queue容器而不是std::queue
容器adapter,正如已经建议的这个另一个答案 https://stackoverflow.com/a/54310728/8012646.
如果你还想坚持std::queue https://en.cppreference.com/w/cpp/container/queue由于某些其他原因,容器适配器,您应该知道它确实通过以下方式提供对底层容器的访问:受保护的数据成员c
.
你可以从std::queue
为了访问底层容器并使用std::find() https://en.cppreference.com/w/cpp/algorithm/find用于在该容器中查找具有此类值的元素的函数模板。然后,只需使用以下方法返回该元素的位置std::distance() https://en.cppreference.com/w/cpp/iterator/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()
成员函数。
如果存在重复项,该解决方案基于std::find()
将返回第一个的位置,即找到具有请求值的第一个元素val
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)