I have an unordered_set<string>
, and I want to consume (i.e. move from) each element in this set and do something with it. Syntactically, I see a few ways of doing this:
unordered_set<string> s = ...;
// 1
for (auto& x : s) {
auto x2 = std::move(x);
do_something(x2);
}
// 2
auto first = std::make_move_iterator(s.begin());
auto last = std::make_move_iterator(s.end());
while (first != last) {
auto x2 = *first++;
do_something(x2);
}
// 3
while (!s.empty()) {
auto it = s.begin();
auto x2 = std::move(*it);
s.erase(it);
do_something(x2);
}
However, all of them give me the concern that I'm modifying the container as I iterate over it. I suspect at least 2 is safe though, because this is valid:
unordered_set<string> s;
vector<string> v;
v.insert(std::make_move_iterator(s.begin()),
std::make_move_iterator(s.end()));
I'm not positive whether any of 1-3 is defined to be safe/valid at all. If so, where can I find the supporting evidence? If not, what are some safe ways to do what I want?
Aucun commentaire:
Enregistrer un commentaire