简体   繁体   English

如何从对向量中删除 c++ 中的 class 对的值项?

[英]How to remove from vector of pairs the value item from pair that is a class in c++?

i am trying to remove all Orders that have old pizza than 3 days:我正在尝试删除所有旧披萨超过 3 天的订单:

i have this vector of pairs:我有这个向量对:

 std::vector<std::pair<Client,Order>> x;
    x.push_back(std::make_pair(Client(2,"Anca"),Order(3,1)));
    x.push_back(std::make_pair(Client(16,"Maria"),Order(1,3)));
    x.push_back(std::make_pair(Client(29,"Alex"),Order(10,5)));

and this class Order:和这个 class 订单:

class Order{
private:
    int amountPizza;
    int pizzaAge;
public:
int getPizzaAge(){
        return pizzaAge;
    }

and i did something like this:我做了这样的事情:

auto it=x.begin();
   while(it!=x.end()){
        if((it->second).getPizzaAge()>3){
            x.erase(std::remove(x.begin(),x.end(),it->second),x.end());
        }
        it++;
    }

and is not working.并且不工作。

Errors:

error: no match for 'operator==' (operand types are 'std::pair<Client, Order>' and 'const Order')
  { return *__it == _M_value; }
 'std::pair<Client, Order>' is not derived from 'const __gnu_cxx::__normal_iterator<_IteratorL, _Container>'
  { return *__it == _M_value; }

Using extra while loop is wrong.使用额外的while循环是错误的。 The moment you erase first element, end() iterator is invalidated.当你删除第一个元素时, end()迭代器就失效了。 Fortunately, std::remove (and std::remove_if ) can handle any number of elements in a single call.幸运的是, std::remove (和std::remove_if )可以在一次调用中处理任意数量的元素。

The second issue is that std::remove can only be used for removing exactly same elements (compared with operator == ).第二个问题是std::remove只能用于删除完全相同的元素(与operator ==相比)。 However, using std::remove_if you can provide a comparison function that is more flexible.但是,使用std::remove_if可以提供更灵活的比较 function。

Your code should look like this:您的代码应如下所示:

auto newEnd = std::remove_if(x.begin(), x.end(), [](const auto& p) {
    return p.second.getPizzaAge() > 3;
});
x.erase(newEnd, x.end());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM