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
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
