gpt4 book ai didi

c++ - 删除列表中的项目,python 风格和 c++ 风格

转载 作者:行者123 更新时间:2023-11-30 01:23:53 24 4
gpt4 key购买 nike

我一直致力于学习 python,并以某种方式想出了以下代码:

for item in list:
while list.count(item)!=1:
list.remove(item)

我想知道这种编码是否可以用 C++ 完成。 (使用 for 循环的列表长度,同时减小其大小)如果不是,谁能告诉我为什么?

谢谢!

最佳答案

我不是一个大 Python 程序员,但上面的代码似乎从列表中删除了重复项。这是一个 C++ 等价物:

list.sort();
list.unique();

至于在遍历列表时修改列表,您也可以这样做。这是一个例子:

for (auto it = list.begin(), eit = list.end(); it != eit; ) {
if (std::count(it, eit, *it) > 1)
it = list.erase(it);
else
++it;
}

希望对您有所帮助。

关于c++ - 删除列表中的项目,python 风格和 c++ 风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14366668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com