如何在C++中只从列表中删除一次特定元素
How to remove specific element from a list only one time in C++?
我正在尝试用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更好的选择。
相关文章:
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 在C++中一次将矢量值写入多个文件
- 高级选择排序 - 在一次迭代中搜索两个元素
- C++ 查找算法:如何找到元素的最后一次出现?
- 一次加载整个缓存行以避免争用其中的多个元素
- C++ 向量元素被最后一次调用push_back替换
- 打印出现一次的字符串数组的第一个元素
- memmove会移动元素(就像前面的方式相同),还是一次抓住整个内存块
- 使用 std::unique 和 vector.erase 删除除最后一次出现的重复元素之外的所有元素
- 用3x3结构元素进行两次形态扩张,等于用6x6结构元素进行一次形态扩张
- 一次向 C++ 向量添加多个元素
- 将多组集排序为升序子序列,每个可用元素出现一次
- 如何将字符串一次推送到一个元素的堆栈中
- 我需要一个 std 函数来检查有多少元素在向量中恰好出现一次
- STD 向量构造元素一次
- 如何在C++中只从列表中删除一次特定元素
- 一个有效的方法,随机选择std::vector的所有元素正好一次而不重新洗牌
- 如何在c++中删除一对重复出现的列表?(保留只出现一次的元素)
- 数组元素的所有排列在C++中一次获取一定数量的元素