加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:05:42 所属栏目:百科 来源:网络整理
导读:在我的代码中,我有一个std :: unordered_set,我需要将数据移动到std :: vector中.我在获取数据时使用std :: unordered_set以确保在转换为std :: vector之前只存储唯一值.我的问题是如何最有效地将内容移动到std :: vector?移动数据后,我不需要std :: unorde
在我的代码中,我有一个std :: unordered_set,我需要将数据移动到std :: vector中.我在获取数据时使用std :: unordered_set以确保在转换为std :: vector之前只存储唯一值.我的问题是如何最有效地将内容移动到std :: vector?移动数据后,我不需要std :: unordered_set.我目前有以下内容:

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

解决方法

在C 17之前,你能做的最好的事情是:

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

集合的元素是const,所以你不能从它们移动 – 移动只是复制.

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

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

虽然你的评论是你的数据是双倍的,但这并不重要.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读