我想从具有特定值的队列中删除元素.怎么办这样的事情?(我正在尝试创建地图和队列的并发混合,目前我尝试在此答案上实现)
所以我目前有这样的代码:
#ifndef CONCURRENT_QUEUED_MAP_H
#define CONCURRENT_QUEUED_MAP_H
#include <map>
#include <deque>
#include <boost/thread.hpp>
#include <boost/thread/locks.hpp>
template <class map_t_1, class map_t_2>
class concurrent_queued_map
{
private:
std::map<map_t_1, map_t_2> _ds;
std::deque<map_t_1> _queue;
mutable boost::mutex mut_;
public:
concurrent_queued_map() {}
map_t_2 get(map_t_1 key) {
boost::mutex::scoped_lock lock(mut_);
return _ds[key];
}
map_t_1 put(map_t_1 key, map_t_2 value) {
boost::mutex::scoped_lock lock(mut_);
_ds.insert(std::pair<map_t_1, map_t_2>(key,value));
_queue.push_back(key);
return key;
}
map_t_2 get_last(map_t_1 key) {
boost::mutex::scoped_lock lock(mut_);
const map_t_1 k = _queue.front();
return _ds[k];
}
void remove_last(map_t_1 key) {
boost::mutex::scoped_lock lock(mut_);
const map_t_1 k = _queue.front();
_ds.erase(k);
_queue.pop_front();
}
void remove(map_t_1 key) {
boost::mutex::scoped_lock lock(mut_);
_queue.erase(std::remove(_queue.begin(), _queue.end(), key), _queue.end());
_ds.erase(k);
}
int size() {
boost::mutex::scoped_lock lock(mut_);
return _ds.size();
}
};
#endif // CONCURRENT_QUEUED_MAP_H
Run Code Online (Sandbox Code Playgroud)
那我该怎么办?如何按值从队列中删除?或者thare是任何类似STL或Boost组件的队列?它意味着什么.front()
,pop_front();
并且push_back(key);
还支持按值搜索和删除?
Ker*_* SB 20
deque是一个序列容器,因此您只能按值删除元素,最好使用删除/擦除习惯用法:
std::deque<T> q;
T val;
q.erase(std::remove(q.begin(), q.end(), val), q.end());
Run Code Online (Sandbox Code Playgroud)
如果您正在使用std::queue
适配器,则根本无法执行此操作,因为适配器仅公开front
/ back
接口,而不是用于迭代或查找语义.
如果您选择将队列实现为std::list
,则使用成员函数remove()
.