【发布时间】:2017-09-09 06:42:48
【问题描述】:
我最近玩了一个std::unordered_set。我怀疑我的 STL 版本会跟踪某些 FILO 数据结构中的非空存储桶(看起来像一个列表)。我想这样做是为了提供完整的std::unordered_set 的O(n) 时间遍历(其中n 表示unordered_set 中的元素数,m 桶和m 比n 大得多)。这改进了在O(m) 时间内对所有桶的简单遍历。
我已经测试过,确实遍历大型且非常稀疏的unordered_sets(使用begin - end)比简单地遍历所有存储桶要快得多。
问题:这个遍历运行时是否有标准保证?或者这只是我的特定标准库的一个特性?
这是我的测试代码:
#include <iostream>
#include <vector>
#include <numeric>
#include <unordered_set>
using namespace std;
void test(vector<int> data, int alloc_size) {
unordered_set<int> set(alloc_size);
for (auto i: data) {
set.insert(i);
}
for (size_t bidx = 0; bidx < set.bucket_count(); ++bidx) {
cout << "[B" << bidx << ":";
for (auto bit = set.begin(bidx); bit != set.end(bidx); ++bit) {
cout << " " << *bit;
}
cout << "] ";
}
cout << " {";
for (auto const & d: set) {
cout << d << " ";
}
cout << "}" << endl;
}
int main() {
test({1, 2, 0}, 3);
test({1, 2, 0, 7}, 3);
test({18, 6, 11, 3, 13, 4}, 20);
test({18, 6, 11, 3, 13, 4, 34}, 20);
}
哪些打印:
[B0: 0] [B1: 1] [B2: 2] [B3:] [B4:] {0 2 1 }
[B0: 0] [B1: 1] [B2: 7 2] [B3:] [B4:] {0 7 2 1 }
[B0:] [B1:] [B2:] [B3: 3] [B4: 4] [B5:] [B6: 6] [B7:] [B8:] [B9:] [B10:] [B11: 11] [B12:] [B13: 13] [B14:] [B15:] [B16:] [B17:] [B18: 18] [B19:] [B20:] [B21:] [B22:] {4 13 3 11 6 18 }
[B0:] [B1:] [B2:] [B3: 3] [B4: 4] [B5:] [B6: 6] [B7:] [B8:] [B9:] [B10:] [B11: 34 11] [B12:] [B13: 13] [B14:] [B15:] [B16:] [B17:] [B18: 18] [B19:] [B20:] [B21:] [B22:] {4 13 3 34 11 6 18 }
似乎begin - end 遍历以相反的顺序报告存储桶,它们变为非空(参见第一行和第三行)。插入已经非空的存储桶不会更改此顺序(参见第二行和第四行)。
【问题讨论】:
标签: c++ c++11 stl c++-standard-library