Moving a vector into an unordered_set
Asked Answered
L

1

9

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.

Lamont answered 18/9, 2020 at 13:36 Comment(4)
Does std::back_inserter(ht) actually compile? I thought back_inserter needs the object to have push_back.Infrequent
Shouldn't that move statement be : std::move(v.begin(), v.end(), std::inserter(ht, ht.end())); ?Hanfurd
@FrançoisAndrieux Oops, you're right! I was more pseudocoding up there to illustrate a point, but didn't realize that what I had was invalid.Lamont
To be precise, you cannot move a vector into an unordered_set, you can only move its contents.Hortensiahorter
H
11

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()));
Hickok answered 18/9, 2020 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.