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::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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有效地将 std::unordered_set 的内容移动到 std::vecto
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
