So it's my first semester on computer science, learning about vectors. For this assignment I had to write a code that read the vector and "eliminated" any repeated elements, then wrote down the results on the same vector.
So, on my limited time and experience, I tried something which is kinda like bubble sort, which yes I know it's terrible and inefficient, but it's just one vector for a first semester assignment.
The logic would go like this: I'd assign a variable called "temp" to have the same value as the first item on the list. Then, I'd compare it with the second item. If they're different, just skip it. If they're equal, then replace the first item with the second, the second with the third, and so forth, always replacing the repeated element with the one after it. After the code is done comparing the temp variable with every other item on the list, it starts all over again but with the temp variable with the same value as the second element, and then the third, and so on. This way the code is kind of "pulling" the list on top of every repeated term.
But I guess I must've done something wrong in the maths of the "for" statements, because the code is skipping some elements, and increasing the size of the vector double confirms it.
#include <cstdlib>
#include <iostream>
#include <fstream>
#define tam 10
using namespace std;
int main(int argc, char** argv) {
int vet[tam] = {1, 2, 3, 5, 7, 11, 3, 0, 7, 17};
int temp,
t = tam;
int j = 0;
for (int i = 0; i < t; i++)
{
temp = vet[i];
for (int n = 1; n < t; n++)
{
if (temp == vet[i+n])
{
t--;
j++;
vet[i+n] = vet[i+n+j];
}
}
cout << vet[i] << endl;
}
return 0;
}
I've tried removing the j and t variables since on hindsight they're probably wholly unecessary but I couldn't find a better logic to replace them, even though I'm preeetty sure they're the main cause of the problem. May need to do more flowcharts in the future.
Edit: So I tried rewriting the code, but couldn't debug or test since VScode isn't cooperating. Could this work?
#include <cstdlib>
#include <iostream>
#include <fstream>
#define tam 20
using namespace std;
int main(int argc, char** argv) {
int vet[tam] = {1, 2, 3, 5, 7, 11, 3, 0, 7, 17, 2, 4, 5, 1, 65, 23, 3, 9, 0, 74};
int temp;
for(int i = 0, j = tam; i <= j; i++)
{
temp = vet[i];
for(int n = 1; n <= j;)
{
if(temp == vet[i+n])
{
vet[i+n] = vet[i+n+1];
n++;
j--;
}
}
cout << vet[i] << endl;
}
return 0;
}