I´m working on a homework project and am stuck with this function. I need to solve the problem twice, using <vector>
and <set>
. We just need to eliminate repeating elements from a vector that´s being passed on as an argument.
This was my first attempt.
vector<int> erase_repeating_elem(vector<int> s) {
int len = s.size();
for (int i = 0; i < len -1; i++) {
for (int j = i + 1; i < len; j++) {
if (s[i] == s[j]){
s.erase (s.begin()+j);
len--;
}
}
}
return s;
}
main(){
vector<int> s = {1, 1, 2, 2, 3, 3};
s = erase_repeating_elem(s);
std::cout << "myvector contains:";
for (unsigned i=0; i<s.size(); ++i)
std::cout << ' ' << s[i];
std::cout << '\n';
return 0;
}
When I tried to run it, i get this: Process returned -1073741819 <0xC0000005>
I thought it might be a memory problem when I erase a vector element as i don´t know if s.size()
is calculated again. So i tried this:
vector<int> erase_repeating_elem(vector<int> s) {
int len = s.size();
for (int i = 0; i < len -1; i++) {
for (int j = i + 1; i < len; j++) {
if (s[i] == s[j]){
s.erase (s.begin()+j);
len--;
}
}
}
return s;
}
I get the same error code. I´m thinking other ways of solving this, maybe swapping repeated elements to the back of the vector an then just using pop_back()
. But I think my solution, if it works, is better.
I´m using a cygwin tool-chain on Code::Blocks, but i´m unable to make the debugger run. Any tips on that?
Also, what would be the correct way to approach it in the <set>
case? I´m guessing just adding the elements to a new set and let it take care itself of the repeating ones.
thank you.