有效地将 std::unordered_set 的内容移动到 std::vector [英] Efficiently moving contents of std::unordered_set to std::vector

查看:42
本文介绍了有效地将 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆