c++ - unordered_set 是否在内部修改?

标签 c++ unordered-set

我一直在阅读 cplusplus.com 网站并尝试确保我的 unordered_set 号码不会以任何方式被修改。该站点表示容器的元素未排序,普通 set 就是这种情况。

该网站还说:

Internally, the elements in the unordered_set are not sorted in any particular order, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their values.

我不知道这到底是什么意思(顺便说一句,你能解释一下吗?)。考虑以下示例:

typedef const std::unordered_set<short> set_t;
set_t some_set = {1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36};

我能否确保上面的集合“some_set”永远不会改变并且数字将始终保持相同的顺序(因为这是这里的目标)? 我也不打算在集合中插入或删除数字。

最佳答案

typedef const std::unordered_set<short> set_t;
set_t some_set = {1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36};

some_set 中数字的变化顺序取决于您对 some_set 进行的操作。 some_set创建后的内容没有定义,但可能不会是{1,3,5,7,9,12,14,16,18,19,21 ,23,25,27,30,32,34,36}。您可以通过一个简单的演示看到这一点:

#include <iostream>
#include <unordered_set>

int main() {
    typedef const std::unordered_set<short> set_t;
    set_t some_set = {1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36};

    for (short s : some_set)
        std::cout << s << std::endl;

    // The order won't change if we don't modify the contents
    std::cout << "AGAIN!" << std::endl;
    for (short s : some_set)
        std::cout << s << std::endl;

    // If we put a bunch of stuff in
    for (short s = 31; s < 100; s += 4)
        some_set.insert(s);

    // The elements from *before* the modification are not necessarily in the
    // same order as before.
    std::cout << "MODIFIED" << std::endl;
    for (short s : some_set)
        std::cout << s << std::endl;
}

关于c++ - unordered_set 是否在内部修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25049160/

相关文章:

c++ - 无限循环不会浪费cpu资源吗?

c++ - C++ Unordered_set 函数中的溢出

c++ - 使 std::unordered_set 的嵌套类型可散列

c++ - 对的无序 multimap

algorithm - 无序集合的中位数

c++ - `std::unororder_set<std::string>` 中的碰撞

c++ - 检测几乎为零并将它们替换为 0.0 或将它们保留为小数字是否更快?

C++ CMake 构建错误:对`boost::throw_exception(std::exception const&) 的 undefined reference

c++ - Direct2D 渲染到命令列表并打印 : Picture Compression

c++ - 对唯一 Ptr 的引用 vector 无效读取