简体   繁体   English

打印unordered_set的元素

[英]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. 我已经使用地图,矢量完成了此操作,但想使用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. 输出是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. 在unordered_set中没有运算符-(),因为它具有向前的迭代器。

Thanks! 谢谢!

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. 一个vector (或者更好的是一个deque )在这里是合适的输出容器,但是您可以在迭代过程中使用一个额外的, 临时的 set来跟踪重复项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM