Pavlo Bazilnskyy
Pavlo Bazilnskyy

Reputation: 336

Problem with erasing elements from the set

I am having troubles with erasing elements from sets. I get BUILD FAILED from:

n2Ar.erase(it);
n3Ar.erase(it);

where it is a pointer received from find() function: e.g. it = n2Ar.find(*i);

The whole listing of the program:

#include <stdio.h>
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>

using namespace std;

#define TESTING_FILE_IN
//#define TESTING_FILE_OUT
//#define DEBUG
//#define SHOW_TIMING

int outputSet(int i) {
    cout << i << endl;
}

/*
 * 
 */
int main() {

    int n1, n2, n3;
    set<int> list, n1Ar, n2Ar, n3Ar;
    set<int>::iterator it;

    scanf("%d", &n1);
    scanf("%d", &n2);
    scanf("%d", &n3);

    int val = 0;

    // Getting lists of voters
    for (unsigned i = 0; i < n1; i++) {
        cin >> val;
        n1Ar.insert(val);
    }

    for (unsigned i = 0; i < n2; i++) {
        cin >> val;
        n2Ar.insert(val);
    }

    for (unsigned i = 0; i < n3; i++) {
        cin >> val;
        n3Ar.insert(val);
    }

    // Processing lists

    for (set<int>::iterator i = n1Ar.begin(); i != n1Ar.end(); ++i) {
        it = n2Ar.find(*i);

        if (it != n2Ar.end()) {
            list.insert(*i);
            n1Ar.erase(i);
            n2Ar.erase(it);

        } else {

            it = n3Ar.find(*i);
            if (it != n3Ar.end()) {
                list.insert(*i);
                n1Ar.erase(i);
                n3Ar.erase(it);
            }
        }
    }

    // Outputting the final list
    cout << list.size() << endl;
    for_each(list.begin(), list.end(), outputSet);

    return 0;
}

I hope you'll be able to help me understand what I am doing wrong in here. I am only starting with C++.

Upvotes: 0

Views: 2828

Answers (3)

Eric Z
Eric Z

Reputation: 14505

There are two problems in your code.

First, you need return a value in the following function, or simply make it return void.

// you should return a value here or make it return void
int outputSet(int i)
{
    cout << i << endl;
}

Second, the iterators in the following iterations of your for-loop are invalidated once you remove the current one. Once an element is removed, its iterator i is also invalidated, so as to the following iterators based on ++i;

And you'll get run-time error because iterator i now points to You need somehow "reset" it.

MSVC Implementation

for (set<int>::iterator i = n1Ar.begin(); i != n1Ar.end(); ++i) {
        it = n2Ar.find(*i);

        if (it != n2Ar.end()) {
            list.insert(*i);
            // the following iterators become invalidated after the
            // current one is removed. You need reset it like
            // i = n1Ar.erase(i);
            n1Ar.erase(i);
            n2Ar.erase(it);

        } else {

            it = n3Ar.find(*i);
            if (it != n3Ar.end()) {
                list.insert(*i);
                // the following iterators become invalidated after the
                // current one is removed. You need reset it like
                // i = n1Ar.erase(i);
                n1Ar.erase(i);
                n3Ar.erase(it);
            }
        }
    }

Edit: Note that returning a new iterator from set::erase() is not a Standard way. That's mainly for the purpose of performance.

A More Portable Solution

The basic idea is to correctly set the next iterator before removing the current one.

   set<int>::iterator i = n1Ar.begin();

   while (i != n1Ar.end())
   {
      it = n2Ar.find(*i);
      if (it != n2Ar.end())
      {
         // the trick is to use "i++" where i is incremented by one while "old" i
         // is removed.
         list.insert(*i);
         n1Ar.erase(i++);
         n2Ar.erase(it);
      }
      else
      {    
         it = n3Ar.find(*i);
         if (it != n3Ar.end())
         {
            list.insert(*i);
            n1Ar.erase(i++);
            n3Ar.erase(it);
         }
         else
         {
            ++i;
         }
      }
   }

Upvotes: 2

eugene_che
eugene_che

Reputation: 1997

  1. Erase method invalidates the iterator i.
  2. Erase method does not return iterator.

EDIT: repeating Eric idea you can use the following code:

for (set<int>::iterator i = n1Ar.begin(); i != n1Ar.end(); )
    if ( n2Ar.erase(*i) || n3Ar.erase(*i) ) {
        list.insert(*i);
        n1Ar.erase(i++);
    } else i++;

Also this problem could be solved using standard algorithms. But this solution seems to be less efficient:

set<int> tmp;
std::set_union( n2Ar.begin(), n2Ar.end(),
    n3Ar.begin(), n3Ar.end(), std::inserter(tmp,tmp.begin()) );
std::set_intersection( n1Ar.begin(), n1Ar.end(),
    tmp.begin(), tmp.end(), std::inserter(list,list.begin()) );

Finally i suggest to use stl for your output (you have to include iterator library):

std::copy( list.begin(), list.end(), std::ostream_iterator<int>(std::cout,"\n"));

Upvotes: 0

BrandonSun
BrandonSun

Reputation: 129

n1Ar.erase(i);

The std::set::erase function invalidates the iterator i and causes the problem. Consider change to the following:

for (set<int>::iterator i = n1Ar.begin(); i != n1Ar.end(); ++i) {
        it = n2Ar.find(*i);

        if (it != n2Ar.end()) {
            list.insert(*i);
            i = n1Ar.erase(i);
            if(i == n1Ar.cend())
                break;
            n2Ar.erase(it);

        } else {

The if(i == n1Ar.cend()) break; check helps to ensure the invalidated iterator will not ruin the loop.

Upvotes: 0

Related Questions