如何使 std::set 插入更快?

发布于 2025-01-19 09:28:10 字数 375 浏览 2 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

热情消退 2025-01-26 09:28:10

如何让 set 函数更快?

您可以通过使用提示来加快速度,因为您知道每次插入都会到集合的末尾:

for(unsigned long i = 0; i < s; i++){
    k.insert(k.end(), i);
}

或者,您也可以使用其他数据结构(例如 std::unordered_set)来加快速度例子。

最重要的是,您可以通过首先不创建如此庞大的集合来加快速度。例如,如果您需要知道某个 unsigned long ul 是否在整数集合 [0, s) 中,那么您可以简单地使用 ul ul unsigned long ul 。 s 而不是创建包含所有整数的集合。

How make set function faster?

You can make this faster by using hints, since you know that every insert is to the end of the set:

for(unsigned long i = 0; i < s; i++){
    k.insert(k.end(), i);
}

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 use ul < s instead of creating the set that contains all the integers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文