Skorpius
Skorpius

Reputation: 2255

Range based for loop to move objects into another container?

Ideally I'd want to do something like this, but is this safe/correct? When moving from some_list to other_list, you're editing the contents of some_list, and every subsequent iteration would be invalidated since the objects all contain null contents.

for (auto& object : some_list) {
    other_list.emplace_back(std::move(object));
}

Is there any way I could make this code more efficient/safer/better or is this the best way I can possibly do this?

Upvotes: 0

Views: 395

Answers (1)

Toby Speight
Toby Speight

Reputation: 30969

Merely modifying the contained objects doesn't invalidate iterators, so this code is safe. There's no need to write the loop yourself, though, since there's the std::move algorithm:

#include <algorithm>
#include <iterator>

template<typename InContainer, typename OutContainer>
void append_back(InContainer& some_list, OutContainer& other_list)
{
    using std::begin;
    using std::end;
    std::move(begin(some_list), end(some_list), std::back_inserter(other_list);
    some_list.clear();
}

Upvotes: 1

Related Questions