pyCthon
pyCthon

Reputation: 12361

std::vector deleting duplicates and then deleting the same index in another vector

I know of how to delete duplicates of a std vector with the STL as such

vec1.erase(std::unique(vec1.begin(), vec1.end()),vec1.end());

but what if i have a different vec2 that is the same length as vec1 and i wish to delete the same indexes that was removed in vec1? Such that if index 2 , 4 and 6 were removed in vec1 , the same would be removed in vec2

Upvotes: 0

Views: 204

Answers (2)

rici
rici

Reputation: 241931

Maybe you want to think of a different datastructure, perhaps vector<pair<vec1_type, vec2_type>>

But here's one way to do it (c++11)

std::vector<int> indices(vec1.size());
std::iota(indices.begin(), indices.end(), 0);
indices.erase(std::unique(indices.begin(), indices.end(),
                          [&](int a, int b){ return vec1[a] == vec1[b]; }),
              indices.end());
auto vec1_iterator = vec1.begin();
auto vec2_iterator = vec2.begin();
for (int i : indices) {
  *vec1_iterator++ = vec1[i];
  *vec2_iterator++ = vec2[i];
}
vec1.erase(vec1_iterator, vec1.end());
vec2.erase(vec2_iterator, vec2.end());

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

Make a copy of the original vector, then walk the two vectors in search of matching items, and erase from the parallel vector when you do not find a match:

vector<int> copy(vec1);
vec1.erase(std::unique(vec1.begin(), vec1.end()),vec1.end());
vector<string> pv = // your "parallel" vector
for (int i = 0 ; i != vec1.size() ; i++) {
    while (copy[i] != vec1[i]) {
        copy.erase(copy.begin()+i);
        pv.erase(pv.begin()+i);
    }    
}

Upvotes: 1

Related Questions