如何删除数组中元素的所有副本? [英] How to remove all copies of an element in an array?

查看:93
本文介绍了如何删除数组中元素的所有副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个n个元素的向量数组,我让用户输入n个整数。现在,我希望我的数组只包含不同的整数。换句话说,我希望它删除整数的所有副本,以便数组只留下每个整数的一次出现。



如果我的向量p = {-1,1,4,1,4,7,3,7,7}



输出应该是:p = {-1,1,3,4,7}



 std :: sort(p.begin(),p.end()); 
for int i = 1 ; p [i] == p [i + 1]; i ++){
do {
p.erase(p.begin) ()+ i + 1);
} while (p [i] == p [i + 1]);
}





但是我得不到合适的输出。有人可以建议对我的代码进行一些更正吗?或者甚至建议用C ++编写更好的代码方法?



我尝试过的方法:



如您所见,我尝试对数组进行排序,以便连续放置整数的所有副本。每当我看到两个具有相同值的元素时,我就会删除下一个元素。

解决方案

你可以使用 std :: unique std :: sort 之后。请参阅 std :: unique - cppreference.com 上的示例代码[ ^ ]。


嗯......看在你的for循环中:终止条件是找到第一个非重复的时间,而不是当你用完比较时。

你需要循环来处理所有元素对,以及if循环中的条件,以确定是否应该删除元素。


找到解决方案!



我用过

 std :: sort(p.begin(),p.end()); 
p.erase(std :: unique(p.begin(),p.end()),p.end());





它会自动删除所有副本并给我新的数组大小!谢谢你的建议! :)


I have a vector array of n elements and I let users to enter n number of integers. Now, I want my array to contain only distinct integers. In other words, I want it to remove all the copies of an integer so that the array is left with only one occurrence of every integer.

If my vector p = {-1, 1, 4, 1, 4, 7, 3, 7, 7}

output should be: p = {-1, 1, 3, 4, 7}

std::sort(p.begin(), p.end());
for (int i=1; p[i] == p[i+1]; i++){
    do {
    p.erase(p.begin() + i+1);
    } while (p[i]==p[i+1]);
}



However I'm not getting a proper output. Can someone suggest some corrections to my code? Or even suggest a better way to code in C++?

What I have tried:

As you can see, I've tried to sort my array so that all the copies of an integer are placed consecutively. Then I'm erasing the immediate next element whenever I see two elements of same value.

解决方案

You may use std::unique after std::sort. See the sample code at std::unique - cppreference.com[^].


Um...look at your for loop: the termination condition is when the first non-duplicate is found, not when you run out of comparisons to make.
You need the loop to work with all elements pairs, and an if condition inside the loop to determine if the element should be removed.


Found the solution!

I used

std::sort(p.begin(), p.end());
p.erase( std::unique( p.begin(), p.end() ), p.end() );



And it automatically deleted all the copies and gave me the new array size! Thanks for the suggestion guys! :)


这篇关于如何删除数组中元素的所有副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆