如何使 std::set 插入更快?
我正在使用 std::set 容器来存储一些标量整数值。我注意到,当我在循环中调用插入操作时,它的速度很慢。我怎样才能让它更快?
下面是一些代表性代码:
std::set<unsigned long> k;
unsigned long s = pow(2,31);
for(unsigned long i = 0; i < s; i++){
k.insert(i);
}
std::cout << k.size() << std::endl;
该代码需要很长时间才能执行。我如何修改此代码(和/或更改我的算法)以使其运行得更快?
I am using the std::set
container to store some scalar integer values. I've noticed that the insert
operation is slow when I call it in a loop. How can I make it faster?
Here is some representative code:
std::set<unsigned long> k;
unsigned long s = pow(2,31);
for(unsigned long i = 0; i < s; i++){
k.insert(i);
}
std::cout << k.size() << std::endl;
This code takes a very long time to execute. How can I modify this code (and/or change my algorithm) in order to make it run faster?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过使用提示来加快速度,因为您知道每次插入都会到集合的末尾:
或者,您也可以使用其他数据结构(例如 std::unordered_set)来加快速度例子。
最重要的是,您可以通过首先不创建如此庞大的集合来加快速度。例如,如果您需要知道某个
unsigned long ul
是否在整数集合 [0, s) 中,那么您可以简单地使用ul
ul
而不是创建包含所有整数的集合。unsigned long ul
。 sYou can make this faster by using hints, since you know that every insert is to the end of the set:
Alternatively, you could potentially make it faster using another data structure, such as
std::unordered_set
for example.Most significantly, you could make it faster by not creating such a massive set in the first place. For example, if you need to know whether some
unsigned long ul
is in the set of integers [0, s), then you can simply useul < s
instead of creating the set that contains all the integers.