0

I am trying to use an unordered_set to keep track of the uniqueness of some char* elements but in this scope the unordered_set modifies and elements even dissapear from it for no reason. I am displaying the elements at the beginning and before modifying it and it does display different elements and I cant get why.

for (unordered_set <char*> ::iterator it = unique_states.begin(); it != unique_states.end(); it++)
                cout << *it << " ";
            cout << endl;
            set <int> state;
            for (int i = 0; i < strlen(states_names[it_states]); i++)
            {
                int index = states_names[it_states][i] - '0';
                for (set <int> ::iterator it = concatenations[index][j].begin(); it != concatenations[index][j].end(); it++)
                    state.insert(*it);
            }
            strcpy_s(temp, "");
            for (set <int> ::iterator it = state.begin(); it != state.end(); it++)
            {
                char aux[2];
                aux[0] = *it + '0';
                aux[1] = '\0';
                strcat_s(temp, aux);
            }
            int position = 0;
            for (unordered_set <char*> ::iterator it = unique_states.begin(); it != unique_states.end(); it++)
                cout << *it << " ";
            cout << endl;
            for (unordered_set <char*> ::iterator it = unique_states.begin(); it != unique_states.end(); it++)
            {
                cout << *it << " ";
                /*if (strcmp(*it, temp) == 0)
                    break;*/
                position++;
            }
            if (unique_states.count(temp) == 0)
                position = it_states + 1;
            cout << "Position : " << position << endl;
            dfa_transitions[it_states].push_back(make_pair(j + 'a', position));
            unique_states.insert(temp);
Some programmer dude
  • 363,249
  • 31
  • 351
  • 550

2 Answers2

2

My guess here is that the problems stems from you using pointers as key in your set.

When you use pointers as keys in a set or a map, it is the pointer itself that is the key, not whatever data they point to. That means two strings (assuming your char* points to null-terminated byte strings) that might compare equal with strcmp might not be equal if they are stored in different locations.

If you want to use strings for keys in your maps or sets, use std::string instead.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550
2

You are inserting inside the unordered_set while iterating over it. See: https://en.cppreference.com/w/cpp/container/unordered_set/insert and specifically:

If rehashing occurs due to the insertion, all iterators are invalidated.

fjardon
  • 7,510
  • 19
  • 29