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