Home > Mobile >  Custom assignment operator on standard library classes
Custom assignment operator on standard library classes

Time:12-30

For example, if I want to make the assignment

std::vector<int> a;
std::vector<std::pair<std::string, int>> b;
a = b;  // a takes all the second components of the pairs in b

Is such a custom assignment possible?

CodePudding user response:

What you seem to want is to transform one container to another. This is usually done with the suitably named std::transform standard function:

std::vector<int> a(b.size());  // Set as same size as the source vector

std::transform(begin(b), end(b), begin(a), [](auto const& pair)
{
    return pair.second;  // Use the second value of each pair from the source
});

CodePudding user response:

Can you overload = to get a = b; push all elements second to a ?

No. Other issues with overloading operators for std types aside, = can only be implemented as member function. You cannot add a member to std::vector<int>.


Can you overload = to get a = b; push all elements second to a ?

Yes. You cannot overload = for std::vector, but you can overload it for a different type:

#include <vector>
#include <utility>
#include <string>


struct pick_second_vector_ref {
    std::vector<int>& t;
    template <typename Source>
    void operator=(const Source& s) {
        for (const auto& e : s) {
            t.push_back(e.second);
        }
    }
};

int main() {
    std::vector<int> a;
    std::vector<std::pair<std::string, int>> b {{"foo",42}};
    pick_second_vector_ref r{a};
    r = b;  // a takes all the second components of the pairs in b
}

However, this is just to illustrate what happens when taking your question too literally. As often a named function is much clearer than an operator overload that does something unexpected. The above main should rather look something like this:

int main() {
    std::vector<int> a;
    std::vector<std::pair<std::string, int>> b {{"foo",42}};
    copy_second(a,b); // no comment needed here because the code 
                      // explains itself !!
}

...ps...

I used = in many places, and now that I've changed the left vector operand I will have to place the necessary transformation function everywhere I used =.

Ok. Go for it. Change the code. It will be simple fixes, because all occurences of = in your code are compiler errors. Remember: Code is written once, but read many times. The 5 minutes you spend fixing the = you will save on the long run when readers do not have to wonder what that = actually does (comments should only be needed to explain code when code alone cannot express it clearly, not the case here).

  • Related