簡體   English   中英

如何從對向量中刪除 c++ 中的 class 對的值項?

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

我正在嘗試刪除所有舊披薩超過 3 天的訂單:

我有這個向量對:

 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)));

和這個 class 訂單:

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

我做了這樣的事情:

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++;
    }

並且不工作。

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; }

使用額外的while循環是錯誤的。 當你刪除第一個元素時, end()迭代器就失效了。 幸運的是, std::remove (和std::remove_if )可以在一次調用中處理任意數量的元素。

第二個問題是std::remove只能用於刪除完全相同的元素(與operator ==相比)。 但是,使用std::remove_if可以提供更靈活的比較 function。

您的代碼應如下所示:

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