user2930006
user2930006

Reputation: 233

Printing the elements of an unordered_set

So I am writing a small code to remove the duplicate characters from a string. I have done it using map, vector but wanted to use unordered_set.

#include <iostream>
#include <unordered_set>
#include <string.h>

using namespace std;

int main() {
    char* str = "abbcdeffg";
    std::unordered_set<char> ump;

    for(int i = 0; i < strlen(str) ; i++)
    {
        ump.insert(str[i]);
    }

    for (auto it = ump.begin(); it != ump.end(); ++it)
    {
        cout << *it;
    }
    return 0;
}

However, the elements are being printed in the reverse order of their insertion. The output is gfedcba. Please can someone explain why?

And what would be the best way to print the elements in the original order. There is no operator--() in unordered_set as it has got forward iterator.

Thanks!

Upvotes: 2

Views: 10773

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

You cannot.

An unordered set does not have any inherent ordering.

That's why it's called an unordered set.

A vector (or, better yet, a deque) would be the appropriate output container here, but you could possibly make use an additional, temporary, set, to keep track of duplicates whilst you iterate.

Upvotes: 6

Related Questions