有效地将 std::unordered_set 的内容移动到 std::vector

Efficiently moving contents of std::unordered_set to std::vector(有效地将 std::unordered_set 的内容移动到 std::vector)
本文介绍了有效地将 std::unordered_set 的内容移动到 std::vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我有一个 std::unordered_set,我需要将数据移动到 std::vector 中.我在获取数据时使用 std::unordered_set 以确保在转换为 std::vector 之前只存储唯一值.我的问题是如何最有效地将内容移动到 std::vector ?移动数据后我不需要 std::unordered_set .我目前有以下:

In my code I have a std::unordered_set and I need to move the data into a std::vector. I'm using the std::unordered_set while getting the data to ensure only unique values are stored prior to converting to a std::vector. My question is how do I move the contents to the std::vector the most efficiently? I don't need the std::unordered_set after the data is moved. I currently have the following:

std::copy(set.begin(), set.end(), std::back_inserter(vector));

推荐答案

在C++17之前,你能做的最好的就是:

Before C++17, the best you can do is:

vector.insert(vector.end(), set.begin(), set.end());

set 的元素是 const,所以你不能离开它们——移动只是复制.

The set's elements are const, so you can't move from them - moving is just copying.

在 C++17 之后,我们得到 extract():

After C++17, we get extract():

vector.reserve(set.size());
for (auto it = set.begin(); it != set.end(); ) {
    vector.push_back(std::move(set.extract(it++).value()));
}

尽管您的评论是您的数据是 doubles,但这并不重要.

Although given your comment that your data is doubles, this wouldn't matter.

这篇关于有效地将 std::unordered_set 的内容移动到 std::vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)