gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:30:15 27 4
gpt4 key购买 nike

我一直在阅读 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com