Home > Back-end >  How can I find the duplicates in my vector and remove them?
How can I find the duplicates in my vector and remove them?

Time:09-19

If its {1,2,2,3,4} it should be {1,2,3,4}. I just can't figure out how to fix my code to do that. The values are random from 1 to 8. I had thought if I counted how many occurrences of a certain number then I could change the value of it if it was greater than 1.

void duplicate(vector<int> &v)
{
    vector <int> num(8);
    vector <int> count(8,0);
    vector <int> index;
    vector <int> temp;
    int k = 0;
    
    for(int i = 0; i < index.size(); i  )
    {
        for(int j = v.size() - 1; j > 0; j--)
        { 
            while(index.at(i) == v.at(j))
            {
                if(index.at(i) == v.at(j))
                {
                    v.at(j) = 0;
                }
            }
            if(index.at(i) 1 == v.at(j))
            {
                v.at(j) = 0;
            }
        }
    }
  
    for(int i = 0; i < v.size(); i  )
    {
        cout << v.at(i);
    }
}

CodePudding user response:

Just create a temporary vector and copy values to it with bookkeeping for duplicates:

int met[9] = {};
std::vector<int> tmp;
for( int val : v ) 
    if( met[val]   == 0 ) 
        tmp.push_back( val );
v.swap( tmp );

CodePudding user response:

You can take two approaches:

  1. As Ted wrote, you can store, for each possible value, whether it's in the vector.
  2. You can sort the vector. A simple way to do this, without algorithms:
std::vector<int> unique(std::vector<int> const& v) {
    std::set<int> tmp(v.begin(), v.end());
    std::vector<int> v2(tmp.begin(), tmp.end());
    return v2;
}

int main() {
    std::vector<int> const v{1, 2, 2, 3, 4};
    std::vector<int> res = unique(v);
    for (auto& x : res) std::cout << x << ' ';
}

CodePudding user response:

I had thought if I counted how many occurrences of a certain number then I could change the value of it if it was greater than 1.

Sure, that's one way. You don't need to count them though. Just do a bookkeeping of the numbers encountered. Example:

void duplicate(std::vector<int> &v) {
    std::vector<bool> taken(8);
    for(int val : v) taken[val-1] = true;
    v.clear();
    for(unsigned i = 0; i < 8;   i) if(taken[i]) v.push_back(i 1);
}

Or do the bookkeeping by setting bits in a std::uint8_t:

void duplicate(std::vector<int> &v) {
    std::uint8_t taken = 0;
    for (int val : v) taken |= 1u << (val - 1);
    v.clear();
    for (unsigned i = 0; i < 8;   i)
        if ((1u << i) & taken) v.push_back(i   1);
}
  • Related