Блог пользователя Qualified

Автор Qualified, история, 6 лет назад, По-английски

I know that set doesn't contain duplicates, but it sorts the elements. I want a data structure that doesn't sort the elements and doesn't contain duplicates.

For example if the data structure contains ints,

Input: 5 4 1 2 5 4 9

Elements in data structure

5 4 1 2 9

Please help.

  • Проголосовать: нравится
  • +19
  • Проголосовать: не нравится

»
6 лет назад, скрыть # |
 
Проголосовать: нравится +8 Проголосовать: не нравится

in Java, you can use a LinkedHashSet

in any language, you can do it yourself using a list (or vector) and a set in combination

»
6 лет назад, скрыть # |
Rev. 2  
Проголосовать: нравится -10 Проголосовать: не нравится

Sorry for mistake in the first time!

You can use map to check if the element in the array or not and a vector array to save the elements.

code

And again sorry for my bad English!

»
6 лет назад, скрыть # |
 
Проголосовать: нравится +10 Проголосовать: не нравится

As said above, you can actually use two data structures for the two properties you desire: one will maintain the order (vector with push_back), and the other will check for duplicates before inserting (set or unordered_set). Code for insertion will be something like this:

vector <int> order;
set <int> seen;

void insert (int element) {
    if (!seen.count (element)) {
        order.push_back (element);
        seen.insert (element);
    }
}