How to go through a set with entered data?

Asked

Viewed 218 times

1

I have a little program that inserts a few integers into a set, and removes when I find the same one, after doing this, I need to bring out all the integers that are still inside the set, but I’m not able to do to go through the set and bring the information I want. Follows the code:

#include <stdlib.h>
#include <iostream> 
#include <set>

using namespace std;

int main (){

int n,k,x;
set <int> di;
set <int>:: iterator it;

cin>>n;
for(int i=0; i<n; i++){
    cin>>k;
    for (int j=0; j<k; j++){
        if (i!=0){
            cin>>x;
            it = di.find(x);
            if (it!=di.end())
                di.erase(it);
        }
        else{
            cin>>x;
            di.insert(x);
        }
    }
}
it = di.begin();
while(it!=di.end()){
    cout<<&it;
    di.erase(it);
    it++;
}
}

2 answers

2

You’re iterating on your std::set and changing the contents of this container at the same time (removing items). Removing elements invalidates the iterator you are currently using, but the method iterator erase( const_iterator pos ) returns a valid iterator for you to continue iteration. You then need to make your iterator equal to the return of the Rase function for the iteration to continue.

Also, you can think of the iterator as a pointer and therefore to print its value you should dereference it as *it and not &it.

it = di.begin();
while(it!=di.end()){
    cout << *it << " "; // *it no lugar de &it e um espaço para separar os itens
    it = di.erase(it); // o iterador retornado pelo erase aqui é o próximo item do seu set
    //it++; -> não funciona quando está removendo o item durante a iteração, porque a remoção do item com o erase invalida o iterador corrente
}

It is not necessary to remove items from the set to print them. You could just use a range-based for loop as the previous response colleague mentioned, or even use the iterator the way you were doing:

it = di.begin();
while(it != di.end()) {
    cout << *it << " ";
    it++;
}

A hint unrelated to the question is to try to use more significant variable names. n, k, x, di are short names that say nothing about what their variables are and make their code difficult to read and understand.

1

To browse any container from the standard C++ library, you can use range-based for:

for (auto elemento : contêiner)
    faz_algo(elemento);

In your case, the container in question is a std::set. The idea is the same:

std::set<int> di{1, 2, 3};
for (int x : di)
    std::cout << x << '\n'; // imprime 1, 2 e 3.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.