Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a pair of repeated occurrences in a list in c++? (keep elements that appear only once)

I've tried using unique but unique removes the duplicate only.

What my program is suppose to do is for example the list contains 1,2,2,2,3,4,4. I am suppose to only remove the the pair of the number that is repeated and the output should be 1,2,3 (a pair of 2 and 4 is removed).

like image 893
lily Avatar asked Dec 07 '25 14:12

lily


2 Answers

Iterate through data and remove pairs (Live code):

list<int> data{1, 2, 2, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 6};

for (auto i = data.begin(); i != data.end();)
{
    auto n = std::next(i);

    if (n == data.end())
        break;

    if (*i == *n)
    {
        i = data.erase(i);
        i = data.erase(i);
    }
    else
        i++;
}

Output

1 2 3 4 5 6 

Also 1 2 3 for 1 2 2 2 3 4 4.

 

Above code works since C++11, if you don't have it, try this:

for (list<int>::iterator i = data.begin(); i != data.end();)
{
    list<int>::iterator n = i; 
    n++;

    if (n == data.end())
        break;

    if (*i == *n)
    {
        i = data.erase(i);
        i = data.erase(i);
    }
    else
    i++;
}
like image 88
masoud Avatar answered Dec 09 '25 02:12

masoud


I would recommend using sort and unique functions to do this.

std::sort (my_vector.begin(), my_vector.end() );
std::vector<int>::iterator it;
it = std::unique (my_vector.begin(), my_vector.end() );
my_vector.resize( std::distance(my_vector.begin(),it) );

Reference: http://www.cplusplus.com/reference/algorithm/unique/ -- this has an example where you can use predicate comparison to customize the behavior of unique.

EDIT -- You may also want to look at std::adjacent_find if you are interested in removing consecutive elements.

EDIT -- If all you care is to delete consecutive elements, first sort the list, and then iterate over it. If two elements are consecutive, delete both of them using std::remove_if or something like that.

like image 22
Bill Avatar answered Dec 09 '25 04:12

Bill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!