有效地将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 :: 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()));
}
尽管您的评论是您的数据是 double
s,但这无关紧要.
Although given your comment that your data is double
s, this wouldn't matter.
这篇关于有效地将std :: unordered_set的内容移动到std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!