Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving a vector into an unordered_set

I have a vector<T> that I would like to initialize unordered_set<T> with. vector<T> will never be used again afterwards.

How I've been doing it is the following

std::vector<T> v{ /* some large amount of data, typically strings */ };
std::unordered_set<T> ht;
std::move(v.begin(), v.end(), std::inserter(ht, ht.end()));

I am wondering if there's a more direct way to do this with unordered_set constructor? Its move constructor doesn't take in a vector.

like image 946
roulette01 Avatar asked Sep 18 '20 13:09

roulette01


1 Answers

This solution actually requires more characters, but it does express the intent more directly:

std::unordered_set<T> ht(std::make_move_iterator(v.begin()),
                         std::make_move_iterator(v.end()));
like image 98
cigien Avatar answered Sep 19 '22 23:09

cigien