¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita0
hard question
How do you delete all the duplicates in the areay? Assume there are 10 integers in the array(numbers could repeat), what algorithm should i use to make sure all the numbers appear only once.
1 Respuesta
+ 2
Sounds like what you really want to use is a set. A set doesn't allow duplicates. If you need to convert an array to a set here is some example code.
#include <iostream>
#include <set>
using namespace std;
int main() {
int arr[] = {1,2,3,4,5,5,6,4,6,7,8};
set<int> s(begin(arr), end(arr));
for(set<int>::iterator it = s.begin(); it != s.end(); ++it) {
cout << *it << endl;
}
return 0;
}
If you just want to use a set outright:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s{1,2,3,4,5,6,7,8,9,2,3,4,5}; //initialize with curly braces
for(set<int>::iterator it = s.begin(); it != s.end(); ++it) {
cout << *it << endl;
}
return 0;
}
OR:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s;
s.insert(1);
s.insert(2);
s.insert(3);
s.insert(4);
s.insert(2); // won't be added to set
s.insert(4); // won't be added to set
s.insert(3); // won't be added to set
for(set<int>::iterator it = s.begin(); it != s.end(); ++it) {
cout << *it << endl;
}
return 0;
}