如何在C++中只从列表中删除一次特定元素

How to remove specific element from a list only one time in C++?

本文关键字:一次 元素 删除 C++ 列表      更新时间:2023-10-16

我正在尝试用C++制作一个简单的win32控制台应用程序,它可以计算有多少匹配具有相同的分数。

示例:
比赛一分为1:1
第二场比赛比分为1:1
第三场比赛的比分是1:2

程序应在控制台中打印以下内容:
有2场比赛比分为1:1
有1场比赛的比分为1:2

我已经创建了"match"对象。

class match
{   
 public:
    int hostScore;
    int guestScore;
    match();
   ~match();
    void input();//This method is to input data in the object.
};

现在我想创建一个函数来计算相同分数的比赛。

void count(list<match> a)
{
     match game;
     int counter;
     do{
           game = a.front(); // I want to take the value of the first element in the list and assign it to "game".
           do{
                  a.deleteSpecificValueOnlyOneTime(game);// I want to delete list element with the value of "game" 1 time
                  counter++
           } while (I can DeleteSpecificValuesOneTime)
           cout<<"There are <<counter<<" matches with score <<game.hostScore<< ":" << game.guestScore<<endl;
           counter = 0;
      } while (a != a.Empty();)// While a is not empty.
}

其想法是从列表中的第一个元素中获取值,删除一次,对其进行计数,然后重复该过程,直到删除所有具有相同值的元素,并计算发生这种情况的次数。

取第n个元素的值,并执行相同操作。

您可以在while循环中使用擦除方法:

std::list<match>::iterator it = a.begin();
while (it != a.end())
{
    if (*it EQUALS game)
        it = a.erase(it);
    }
    else {
        it++;
    }
}

最简单的选择是将所有元素放在一个集合中,然后将它们检索回列表。

为了能够做到这一点,您必须为匹配定义一个较少的运算符:

bool operator<(const match &lhs, const match &rhs){
  if(lhs.hostScore==rhs.hostScore){
    return lhs.guestScore<rhs.guestScore;
  }
  return lhs.guestScore<rhs.guestScore;
}

之后你几乎完成了快速完成:

void make_elements_unique(std::list<match> &games){
  std::set<match> unique;
  //put all elements into the set:
  unique.insert(games.begin(), games.end());
  //clear list and copy all elements from the set to the list, they are unique:
  games.assign(unique.begin(), unique.end());
}

如果你想寻找性能,并且有很多游戏,那么比unordered_set(c++11)会是比std::set更好的选择。