-
Dangerous reference !
Hi everyone, I was a solving a problem of changing one vector in a way of removing all the elements of the vector that the other vector has. And unfortunately it doesn't work. Here is the code :
Code:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
template <typename type>
void function(vector<type>&a,vector<type>&b){
for(int i=0;i<a.size();i++){
int k(0);
for(int j=0;j<b.size();j++){
if(a[i]==b[j])
k=1;
}
if(k==1){
for(int p(i);p<a.size()-1;p++){
a[p]=a[p+1];
}
a.resize(a.size()-1);
}
}
}
int main(){
int n;
cout<<"How many words ?";
cin>>n;
cin.ignore(1000,'\n');
vector<string>s(n);
for(int i=0;i<n;i++){
getline(cin,s[i]);
}
int b;
cout<<"How many words now?";
cin>>b;
cin.ignore(1000,'\n');
vector<string>j(b);
for(int u(0);u<b;u++){
getline(cin,j[u]);
}
function(s,j);
cout<<endl;
for(int i=0;i<s.size();i++){
cout<<s[i]<<endl;
}
return 0;
}
-
Perhaps you could edit the code to fix code tags and the indentation.
Anyway, your algorithm is probably skipping values when two consequtive items need to be removed. That's because, after you erase an item, you increment the counter anyway, even though the next item to check is at the same index.
Suppose you want to remove B and C:
Code:
ABCDE
^
i
Next iteration:
ACDE
^
i
-
So essentially you want to perform a set difference on the two vectors.
Are the vectors both sorted? If so, there's a std library algorithm that will make it a lot more efficient.
Code tags ... you're doing it wrong.
-
Thank you very much. You are completely right, it skips... So i put i-- after resize and it works now.