是否可以按值删除队列元素? [英] Is it possible to remove queue element by value?

查看:245
本文介绍了是否可以按值删除队列元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从具有特定值的队列中删除元素。如何做这样的事情? (我试图创建一个并行的混合映射和队列,目前我尝试实现在 this answer

I want to remove element from queue with specific value. How to do such thing? (I am trying to create a concurrent mixture of map and queue and currently I try to implement on this answer)

所以我目前有这样的代码: / p>

So I currently have such code:

#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

那么我该怎么办?如何从队列中删除值?或者是任何STL或Boost组件是相似的队列?这意味着它会有 .front() pop_front(); ;

So what shall I do? How to remove from queue by value? Or thare is any STL or Boost component that is alike queue? Meaning it would have .front(), pop_front(); and push_back(key); and also support search and erase by value?

推荐答案

deque是一个序列容器,因此您只能通过 value 删除元素,最好使用remove / erase idiom:

A deque is a sequence container, so you can only remove elements by value, which is best done with the remove/erase idiom:

std::deque<T> q;
T val;

q.erase(std::remove(q.begin(), q.end(), val), q.end());

如果使用 std :: queue 适配器,那么你完全不能这样做,因为适配器只暴露 / 接口

If you are using the std::queue adapter, then you cannot do this at all, because the adapter only exposes the front/back interface and is not intended for iteration or lookup semantics.

如果您选择以 std :: list 实现您的队列,请改用成员函数 remove()

If you choose to implement your queue as an std::list, then use the member function remove() instead.

这篇关于是否可以按值删除队列元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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