Sunday 15 February 2015

c++ - What's the canonical way of overloading the compound assignment operator? -



c++ - What's the canonical way of overloading the compound assignment operator? -

seems kind of tough problem because can't add together new fellow member functions vector. form avoids to the lowest degree amount of copies:

std::vector<t>& operator+=(std::vector<t>& lhs, const std::vector<t>& rhs)

but fails self-assignment, 1 works self-assignment is:

template <typename t> std::vector<t>& operator+=(std::vector<t>& lhs, std::vector<t> rhs) { lhs.insert(lhs.end(), rhs.begin(), rhs.end()); homecoming lhs; }

but requires copy. what's right way of doing this?

it ambiguous in question above forms "don't work" because appear work ints (although not std::strings). pointed out because it's undefined behavior.

the problem with:

template <typename t> std::vector<t>& operator+=(std::vector<t>& lhs, const std::vector<t>& rhs) { lhs.insert(lhs.end(), rhs.begin(), rhs.end()); homecoming lhs; }

is not signature, it's passing iterators insert become invalid before insert has completed.

just utilize the right technique appending vector itself, , no re-create needed.

template <typename t> void concat_in_place(std::vector<t>& lhs, const std::vector<t>& rhs) { auto left_count = lhs.size(); auto right_count = rhs.size(); lhs.resize(left_count + right_count); std::copy_n(rhs.begin(), right_count, lhs.begin() + left_count); }

c++ c++11

No comments:

Post a Comment