有没有一种简单的方法可以通过 C++ 中的值获取元素在 std::queue
中的位置?
例如:
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
容器适配器,正如 this other answer 中已经建议的那样.
如果你还想坚持std::queue
由于某些其他原因,容器适配器,您应该知道它确实通过protected 数据成员c
提供对底层容器的访问。
您可以从 std::queue
派生以访问底层容器并使用 std::find()
用于在该容器中查找具有此类值的元素的函数模板。然后,只需使用 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()
成员函数返回的索引。
如果有重复,这个基于std::find()
的解决方案将返回第一个的位置,即找到的第一个具有请求值的元素val
.
关于c++ - 通过值获取 std::queue 中元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54310262/